Files
Code
Module: mMain
'Macro shows how to view the full contents of a SolidWorks materials database (SLDMAT), which _
is simply an XML file, using the File System Object. This code could form the basis for _
a macro that modifies the custom properties in custom material databases. Note that _
XML-parsing libraries already exist for VBA, like MSXML (Reference: "Microsoft XML, v6.0")
'Preconditions: part is open
'Result: the contents of the database (an XML file) is printed to the immediate window
'Note:
'-A reference to Microsoft Scripting Runtime is required.
'-Since 2+ material databases with the same name can exist (although they reside in different _
folders, it is possible that this macro will return the contents of the wrong database. _
The reason being, the for loop below is exited as soon as the first match is found. A _
more robust version of this macro might prompt the user to select from a list of all _
possibilities.
'Written by Keith Rice
'CADSharp LLC
'www.cadsharp.com
Option Compare Text
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swPart As SldWorks.PartDoc
Dim strDBName As String
Dim vMatDBPaths As Variant
Dim strMatDBPath As String
Dim strMatDBName As String
Dim i As Integer
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swPart = swModel
swPart.GetMaterialPropertyName2 "Default", strMatDBName
'Default materials database is represented by zero-length string
If strMatDBName = "" Then strMatDBName = "solidworks materials"
vMatDBPaths = swApp.GetMaterialDatabases
Dim strTemp As String
For i = 0 To UBound(vMatDBPaths)
'Remove folder path
strTemp = Right(vMatDBPaths(i), Len(vMatDBPaths(i)) - InStrRev(vMatDBPaths(i), "\"))
'Remove extension
strTemp = Left(strTemp, Len(strTemp) - 7)
If strTemp = strMatDBName Then
strMatDBPath = vMatDBPaths(i)
Exit For
End If
Next i
'Print the material database XML to the immediate window
Dim fso As New FileSystemObject
Dim file As file
Dim textstream As textstream
Dim strLine As String
If fso.FileExists(strMatDBPath) Then
Set file = fso.GetFile(strMatDBPath)
Set textstream = file.OpenAsTextStream(ForReading)
Do Until textstream.AtEndOfStream
strLine = textstream.ReadLine
Debug.Print strLine
Loop
End If
textstream.Close
Set textstream = Nothing
Set fso = Nothing
End Sub