Files
Get all SolidWorks models in a folder
Code
Module: mMain
'Demonstrates how to write a function that gets all SolidWorks models in _
a folder, with an option to look in sub-folders as well.
'GetSolidWorksModels parameters:
' strFolder - the folder to look in
' vExtensions - an array of extensions to search for
' blnIncludeSubfolders - whether to include subfolders in the search
' ByRef myCol - the collection containing the file paths
'Preconditions: VBA project includes reference to "Microsoft Scripting Runtime"
'Results: See immediate window.
'Written by Keith Rice
'CADSharp LLC
'www.cadsharp.com
Const FOLDER As String = "C:\"
Sub main()
Dim colModelPaths As New Collection
Dim vExtensions As Variant
vExtensions = Array("SLDPRT", "SLDASM", "SLDDRW")
If GetSolidWorksModels(FOLDER, vExtensions, False, colModelPaths) Then
Debug.Print "Files found:"
Dim i As Integer
For i = 1 To colModelPaths.Count
Debug.Print vbTab & colModelPaths.Item(i)
Next i
Else
Debug.Print "Failed to get SolidWorks models in " & FOLDER
End If
End Sub
Private Function GetSolidWorksModels(strFolder As String, vExtensions As Variant, _
blnIncludeSubfolders As Boolean, ByRef myCol As Collection) As Variant
On Error GoTo ErrHandler
Dim fso As New FileSystemObject
Dim myFolder As FOLDER
Dim mySubFolder As FOLDER
Dim files As Variant
Dim file As Variant
Dim myFile As file
Dim strExtension As String
Dim i As Integer
Set myFolder = fso.GetFolder(strFolder)
Set files = myFolder.files
For Each file In files
Set myFile = file
strExtension = fso.GetExtensionName(myFile.Path)
'Prevent temporary files from being collected
If Left(fso.GetFileName(myFile.Path), 2) <> "~$" Then
For i = 0 To UBound(vExtensions)
If LCase(strExtension) = LCase(vExtensions(i)) Then _
myCol.Add myFile.Path
Next i
End If
Next
If blnIncludeSubfolders Then
For Each mySubFolder In myFolder.SubFolders
GetSolidWorksModels mySubFolder.Path, vExtensions, blnIncludeSubfolders, myCol
Next
End If
GetSolidWorksModels = True
Exit Function
ErrHandler:
Debug.Print "ERROR: " & Err.Number & " " & Err.Description
GetSolidWorksModels = False
End Function