MACRO LIBRARY

Create 3D points from data in Excel or text file

Free public access. No account or subscription required.

Instructions

Preconditions
SolidWorks is open.
Result
Points are added to 3D sketch in new or current part or assembly using coordinates from an excel or text file.

Files

Create 3D points from data in Excel or text file

Code

Module: main

'This corrects the issue on x64 computers of the VBA form opening behind the SolidWorks _
    application window. It is recommended that user the insert their macro code into the _
    form module rather than this module. If the user changes the name of the form from _
    UserForm1 to something else, they will need to line containing this form name.
    
'This is a heavily modified version of the macro provided in S-013887
'Modified by Keith Rice
'CADSharp LLC
'www.cadsharp.com
    
Option Explicit
    
'Determines whether a file is an executable (.exe) file, and if so, which subsystem runs the executable file.
Declare Function GetBinaryType Lib "kernel32" Alias "GetBinaryTypeA" (ByVal sFileName As String, ByRef BinType As Long) As Long
    
'Retrieves a handle to the top-level window whose class name and window name match the specified strings.
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
    
'Changes the size, position, and Z order of a child, pop-up, or top-level window.
Declare Function SetWindowPos Lib "user32" (ByVal hWnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
    
Sub main()
    Dim lBinaryType As Long
    Dim hWnd As Boolean     'window handle
    Dim swApp As SldWorks.SldWorks
    Set swApp = Application.SldWorks
    
    'This function returns lBinaryType as 6 for x64 and 0 for x86 (32 bit)
    GetBinaryType swApp.GetExecutablePath & "sldworks.exe", lBinaryType
    
    'Show form
    UserForm1.Show vbModeless
    
    'If x64 make form on top
    If lBinaryType = 6 Then
        hWnd = FindWindow(vbNullString, UserForm1.Caption)
        'See this article for information on SetWindowPos arguments: _
            http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545(v=vs.85).aspx
        'The flags are currently set for SWP_NOMOVE and SWP_NOSIZE
        SetWindowPos hWnd, -1, 0, 0, 0, 0, 1 + 2
    End If
End Sub

Form: UserForm1

'Keith Rice
'CADSharp LLC
'www.cadsharp.com
'Written in SolidWorks 2011
'Do not re-use code in this form without proper attribution.
    
'Preconditions: SolidWorks is open.
'Postconditions: Points are added to 3D sketch in new or current part or assembly _
    using coordinates from an excel or text file.
    
Option Explicit
    
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSkMan As SldWorks.SketchManager
    
Dim factor As Single
Dim strFileName As String
Dim strPoints() As String
Dim row As Integer
Dim vPointsSplit As Variant
Dim dblX() As Double
Dim dblY() As Double
Dim dblZ() As Double
Dim i As Integer
Dim z As Integer
    
Dim strPartTemplate As String
Dim strAssyTemplate As String
    
Private Sub cmdAbout_Click()
    MsgBox "Version 1.0" & vbCrLf & "SolidWorks API code by Keith Rice" & vbCrLf & "CADSharp LLC" & vbCrLf & "www.cadsharp.com"
End Sub
    
Private Sub cmdBrowse_Click()
    Dim strFilter As String
    Dim strFileOptions As Long      'output
    Dim strFileConfig As String     'output
    Dim strFileDispName As String   'output
    
    strFilter = "Excel, CSV, or text file|*.xls; *.xlsx; *.xlsm; *.csv; *.txt|"
    strFileName = swApp.GetOpenFileName("Open file", "", strFilter, strFileOptions, strFileConfig, strFileDispName)
    txtPath.Text = strFileName
End Sub
    
Private Sub cmdCreate_Click()
    'get template locations
    strPartTemplate = swApp.GetUserPreferenceStringValue(swUserPreferenceStringValue_e.swDefaultTemplatePart)
    strAssyTemplate = swApp.GetUserPreferenceStringValue(swUserPreferenceStringValue_e.swDefaultTemplateAssembly)
    
    'get factor for unit conversion
    Select Case cboUnits.Value
        Case "mm"
            factor = 0.001
        Case "m"
            factor = 1
        Case "in"
            factor = 25.4 * 0.001
        Case "ft"
            factor = 304.8 * 0.001
    End Select
    
    'create / connect to solidworks model
    If optActiveDoc.Value = True Then
        Set swModel = swApp.ActiveDoc
        If swModel Is Nothing Then
            MsgBox "Part or assembly document not active."
            Exit Sub
        End If
        If swModel.GetType = swDocDRAWING Then
            MsgBox "Part or assembly document not active."
            Exit Sub
        End If
    ElseIf optNewPart.Value = True Then
        Set swModel = swApp.NewDocument(strPartTemplate, 0, 0, 0)
        If swModel Is Nothing Then
            MsgBox "Template not found."
            Exit Sub
        End If
    ElseIf optNewAssy.Value = True Then
        Set swModel = swApp.NewDocument(strAssyTemplate, 0, 0, 0)
        If swModel Is Nothing Then
            MsgBox "Template not found."
            Exit Sub
        End If
    End If
    
    'Get point data
    If InStr(1, Right(txtPath.Text, 4), "xls") <> 0 Then
        'Get data from excel file
        Call GetPointsFromExcel
    ElseIf InStr(1, Right(txtPath.Text, 3), "txt") <> 0 Then
        'Get data from text file
        Call GetPointsFromText
    ElseIf InStr(1, Right(txtPath.Text, 3), "csv") <> 0 Then
        'Get data from csv file
        Call GetPointsFromExcel
    Else
        MsgBox "Please browse for an Excel or text file."
        Exit Sub
    End If
    
    'extract and test the X, Y, and Z coordinates from each element in the string array
    ReDim dblX(UBound(strPoints)) As Double
    ReDim dblY(UBound(strPoints)) As Double
    ReDim dblZ(UBound(strPoints)) As Double
    For i = 0 To UBound(strPoints)
        'in the event that someone did skip a line in the text file, this will prevent _
            any errors. when the sketch manager creates a point for that element of the _
            array, it will be 0, 0, 0 --- the default values of those elements
        If strPoints(i) <> "" Then
            vPointsSplit = Split(strPoints(i), ",")
            For z = 0 To UBound(vPointsSplit)
                If IsNumeric(vPointsSplit(z)) = False Then
                    MsgBox "Data can only include numbers." & vbCrLf & "(Not including commas.)"
                    Exit Sub
                End If
            Next z
            On Error GoTo ErrorHandling:
            dblX(i) = vPointsSplit(0) * factor
            dblY(i) = vPointsSplit(1) * factor
            dblZ(i) = vPointsSplit(2) * factor
        End If
    Next i
    
    'create the points
    swModel.Insert3DSketch2 True
    Set swSkMan = swModel.SketchManager
    swSkMan.AddToDB = True
    For i = 0 To UBound(dblX)
        swSkMan.CreatePoint dblX(i), dblY(i), dblZ(i)
    Next i
    swModel.Insert3DSketch2 True
    swModel.ViewZoomtofit2
    Call cleanup
    Exit Sub
    
ErrorHandling:
MsgBox "Error reading data."
Call cleanup
End Sub
    
Private Sub UserForm_Activate()
    Set swApp = Application.SldWorks
    cboUnits.AddItem "mm"
    cboUnits.AddItem "m"
    cboUnits.AddItem "in"
    cboUnits.AddItem "ft"
End Sub
    
Private Sub GetPointsFromExcel()
    Dim xlApp As Excel.Application
    Dim xlWB As Excel.Workbook
    
        Set xlApp = CreateObject("Excel.Application")
        xlApp.Visible = False
        Set xlWB = xlApp.Workbooks.Open(strFileName)
        'find number of rows with data
        row = 1
        With xlWB.Worksheets(1)
            While Cells(row, 1).Value <> ""
                row = row + 1
            Wend
        End With
        'resize array accordingly and get data in rows
        ReDim strPoints(row - 2)
        row = 1
        With xlWB.Worksheets(1)
            While Cells(row, 1).Value <> ""
                strPoints(row - 1) = Cells(row, 1).Value
                row = row + 1
            Wend
        End With
        xlWB.Close False
        xlApp.Quit
        Set xlApp = Nothing
        Set xlWB = Nothing
End Sub
    
Private Sub GetPointsFromText()
    Dim oFSO As FileSystemObject     'requires reference to microsoft scripting runtime
    Dim oFile As file
    Dim oTextStream As TextStream
    Dim strLines() As String
    
    'Set oFSO = CreateObject("Scripting.Filesystemobject")
    Set oFSO = New FileSystemObject
    row = 1
    If oFSO.FileExists(strFileName) = True Then
        Set oFile = oFSO.GetFile(strFileName)
        Set oTextStream = oFile.OpenAsTextStream
        'count number of lines and resize array accordingly
        strLines = Split(oTextStream.ReadAll, vbCrLf)   'we could use this to get each _
            line, but we'll keep using the FSO just as a demonstration
        Set oTextStream = oFile.OpenAsTextStream    'need to reset it after using ReadAll, _
            otherwise we are already at the end of the stream and will never enter the loop.
        ReDim strPoints(UBound(strLines))
        Do Until oTextStream.AtEndOfStream
            strPoints(row - 1) = oTextStream.ReadLine
            row = row + 1
        Loop
    End If
    Set oFSO = Nothing
    Set oFile = Nothing
    Set oTextStream = Nothing
End Sub
    
Sub cleanup()
    If chkClose.Value = True Then End
    swSkMan.AddToDB = False
    Set swModel = Nothing
    Set swSkMan = Nothing
End Sub