You are on page 1of 11

10/27/2016

SolidAPI
0

More NextBlog

CreateBlog SignIn

Feb16,2016

BlogArchive

ExtendingSOLIDWORKSInterferenceDetection

2016(2)
February(1)
ExtendingSOLIDWORKS
InterferenceDetection
January(1)
2015(1)
2012(4)

AboutMe

MikeSpens
Viewmycomplete
profile

Modelc/oMalcomMa

NowavailableonGoogleeBooks!

HaveyoueverruntheSOLIDWORKS
InterferenceDetectiontoolandthought,
"IfIcouldonlysavethislistof
interferingcomponents?"
Iwastalkingwithacolleaguewho
recentlyhitthisproblemsquareon.He
wantedtoworkthroughhundredsof
interferenceproblemsresultingfromthe
lacklusterdesignofaprintedcircuit
board.Herecomesthe
SOLIDWORKSAPItotherescue!
Followers

ThefundamentalscomefromanAPI
helpexamplehere.Minor
modificationsweremadetostorethe
databeingsenttotheDebugwindow
andsaveittoatextfile.Finally,to
givethemacrosomerealflair,adding
theoptiontoturntheinterfering
volumesintobodiesinapart.
Ratherthanpackingallofthecodeintothemacro'smainprocedure,I'vecreatednew
classesnamedInterferenceCheckingandLocalInterferences.Thesetwoclasseshave
alloftheroutinesneededandcanbecalledfromaseparateapplicationifyoudon'twant
tojustrunitasamacro.

Followers(12)

Follow

Downloadthemacrosourcecodehere(VB.NET)
Implementthenewclasslikethis.

PublicSubmain()

http://www.solidapi.com/

1/11

10/27/2016

SolidAPI
DimmodelAsModelDoc2=swApp.ActiveDoc
DimintCheckAsNewInterferenceChecking
intCheck.CheckInterference(model,swApp)
intCheck=Nothing
EndSub
Thefollowingisallcodefortheproject,notincludingthecallingreference.

ImportsSolidWorks.Interop.sldworks
ImportsSolidWorks.Interop.swconst
ImportsSystem.Runtime.InteropServices
ImportsSystem
ImportsSystem.Diagnostics
ImportsSystem.Windows.Forms
PublicClassInterferenceChecking
PublicSubCheckInterference(ByValmodelAsModelDoc2,_
ByRefswAppAsSldWorks)
DimswModelDocAsModelDoc2=model
DimswAssemblyDocAsAssemblyDoc
DimpIntMgrAsInterferenceDetectionMgr
DimvIntsAsObject
DimiAsLong
DimjAsLong
DiminterferenceAsIInterference
DimvCompsAsObject=Nothing
DimcompAsComponent2
DimvolAsDouble
DimvTransAsObject=Nothing
DimretAsBoolean
DimrepMessageAsString="Interferencereportfor:"_
&model.GetTitle&vbCrLf
swAssemblyDoc=swModelDoc
pIntMgr=swAssemblyDoc.InterferenceDetectionManager
'Specifytheinterferencedetectionsettingsandoptions
pIntMgr.TreatCoincidenceAsInterference=False
pIntMgr.TreatSubAssembliesAsComponents=True
pIntMgr.IncludeMultibodyPartInterferences=True
pIntMgr.MakeInterferingPartsTransparent=False
pIntMgr.CreateFastenersFolder=True
pIntMgr.IgnoreHiddenBodies=True
pIntMgr.ShowIgnoredInterferences=False
pIntMgr.UseTransform=True
'Specifyhowtodisplaynoninterferingcomponents
pIntMgr.NonInterferingComponentDisplay=_
swNonInterferingComponentDisplay_e._
swNonInterferingComponentDisplay_Wireframe
'Runinterferencedetection
vInts=pIntMgr.GetInterferences
Debug.Print("Totalnumberofinterferences:"_
&pIntMgr.GetInterferenceCount)
repMessage=repMessage_
&"Totalnumberofinterferences:"_
&pIntMgr.GetInterferenceCount&vbCrLf
'Getinterferingcomponentsandtransforms
ret=pIntMgr.GetComponentsAndTransforms(vComps,vTrans)
Dimbodies(0)AsObject
'Getinterferenceinformation
Fori=0ToUBound(vInts)

http://www.solidapi.com/

2/11

10/27/2016

SolidAPI
Debug.Print("Interference"&(i+1))
repMessage=repMessage&"Interference"&(i+1)_
&vbCrLf
interference=vInts(i)
ReDimPreservebodies(i)
bodies(i)=interference.GetInterferenceBody()
Debug.Print(_
"Numberofcomponentsinthisinterference:"_
&interference.GetComponentCount)
repMessage=repMessage_
&"Numberofcomponentsinthisinterference:"_
&interference.GetComponentCount&vbCrLf
vComps=interference.Components
Forj=0ToUBound(vComps)
comp=vComps(j)
DimcNameAsString=comp.ComponentReference
IfcName=""ThencName=comp.Name2
Debug.Print(""&cName)
repMessage=repMessage&""&cName&vbCrLf
Nextj
vol=interference.Volume
DimvolMessageAsString=_
"Interferencevolume:"_
&Format((vol*1000000000),"#.###")&"mm^3"
Debug.Print(volMessage)
repMessage=repMessage&volMessage&vbCrLf
Nexti
'Stopinterferencedetection
pIntMgr.Done()
IfMsgBox("Savereporttofile?",MsgBoxStyle.YesNo_
+MsgBoxStyle.Question)=MsgBoxResult.YesThen
'writeoutthereport
WriteReport(repMessage,model.GetTitle&".txt")
EndIf
IfMsgBox("Createintereferencevolumepart?"&vbCrLf_
&"*Complexinterferencecantaketime.",_
MsgBoxStyle.YesNo+MsgBoxStyle.Question)_
=MsgBoxResult.YesThen
'Createapartwiththebodiesarray
DimintfAsNewLocalInterferences(bodies)
intf.CreateInterferingBodiesPart(swApp)
intf=Nothing
EndIf
EndSub
PrivateSubWriteReport(ByValrepMessageAsString,_
OptionalByValdefaultNameAsString="")
DimsfdAsNewSaveFileDialog
sfd.DefaultExt="txt"
sfd.Filter="Textfile(*.txt)|*.txt"
sfd.FileName=defaultName
sfd.OverwritePrompt=True
DimdiaResAsDialogResult=sfd.ShowDialog()
IfdiaRes=DialogResult.OKThen
DimfilePathAsString=sfd.FileName
My.Computer.FileSystem.WriteAllText(sfd.FileName,_
repMessage,False)
Process.Start(sfd.FileName)
EndIf
EndSub
EndClass

http://www.solidapi.com/

3/11

10/27/2016

SolidAPI
ClassLocalInterferences
DimintBodiesAsObject
FriendSubCreateInterferingBodiesPart(_
ByRefswAppAsSldWorks)
IfintBodiesIsNothingThen
ExitSub
EndIf
DimpartAsPartDoc
part=swApp.NewPart()
ForiAsInteger=0ToUBound(intBodies)
DimfeatAsFeature
feat=part.CreateFeatureFromBody3(intBodies(i),_
False,swCreateFeatureBodyOpts_e.swCreateFeatureBodyCheck_
+swCreateFeatureBodyOpts_e.swCreateFeatureBodySimplify)
Nexti
EndSub
PublicSubNew(ByValbodiesAsObject)
intBodies=bodies
EndSub
EndClass
PostedbyMikeSpens

Nocomments:

Recommend this on Google

Jan26,2016

SOLIDWORKSDocumentManagerAPIToolkit

TheSOLIDWORKSDocumentManagerisapowerfultoolusedforreportingcontentand
manipulatingSOLIDWORKSparts,assembliesanddrawings.Iveusedittoexport
custompropertiesfromthousandsofSOLIDWORKSfilesinseconds!Itcanbeusedto
readbillofmaterialsandothertablesfromdrawingsaswellasupdatereferenceswhen
filesarerenamed.
But,justlikeanyotherproject,itcantaketimetogetstartedandgetfamiliarwiththe
callsneeded.Tomakethatalleasier,IveputtogetheraVisualStudio2010projectin
VB.NETImcallingtheDocumentManagerToolkit.
IllbepresentingthetoolkitalongwithageneraldiscussionoftheSOLIDWORKS
DocumentManageratSOLIDWORKSWorld2016inDallas,TXnextweek.Hopetosee
youthere!

http://www.solidapi.com/

4/11

10/27/2016

SolidAPI
Whatsinthetoolkit?youask?Downloadtheprojecthereforasampleimplementation
andreaduponthegeneralfunctionalitybelow.
DocumentManagerToolkitDownload
DocumentManagerPresentationPDF(SOLIDWORKSWorld2016)

MyDocManClass
TheMyDocManclassisthebasisforthetoolkit.Ittakescareoflicensevalidationanda
plethoraofcommonoperationssharedbelow.Thefunctionsandproceduresare
documentedintheprojecttomakeiteasiertouseinyourowntools.
InstantiatingtheclasswillconnecttotheSOLIDWORKSDocumentManagerandisbuilt
toreadyourDocumentManagerlicensefromatextfilenamedDocMgrLicense.txtfrom
C:\.EdittheGetDocManAppproceduretoinsertandcompileyourlicense,redirectthe
licensefilelocation,orpointtolicenseinformationsavedinMy.Settings.

CommonOperations
GetDocument
GetAllProperties
GetDelimitedTableText
GetBOMTableNames
GetMissingReferences
GetDocument
Summary:
Fromafullfilepath,returnanopenedSwDMDocument.
Parameters:
FilePath:fullpathtothedesiredSOLIDWORKSfile
forReadOnly:Truetoopenthefilereadonly,Falsetoopenwithwriteaccess.
ReturnValues:
ReturnsanSwDMDocumentinterfaceifsuccessful.
GetAllProperties
Summary:
Functiontoreadallfileandconfigurationspecificcustompropertiesfromadocument.
Parameters:
dmDoc:DocumentManagerdocument
ReturnValues:
Atabdelimitedstringcontainingallconfigurationnames,propertiesandvalues.Anempty
stringintheconfigurationcolumnindicatesafileproperty.
Remarks:
Eachlineinthestringwillterminateinacarriagereturncharacter.
GetDelimitedTableText
Summary:
Getalltextfromanamedtablewiththedesireddelimiter.
Parameters:
tableName:NameofthetableintheSOLIDWORKSfile
dmDoc:theSwDMDocument10interfacecontainingthetable
delimiter:thedesiredcolumndelimiter
ReturnValues:
Astringrepresentingthetextoftheentiretable,includingheaders.Returncharactersare
appliedbetweenrows.
GetBOMTableNames
Summary:
Getsalltablenamesfromadocument.
Parameters:

http://www.solidapi.com/

5/11

10/27/2016

SolidAPI
dmDoc:Thedesireddocumentcontainingtables.
ReturnValues:
AnarrayofstringsinanObject.
Remarks:
UsethisfunctionbeforecallingGetDelimitedTableTexttoretrieveavalidBOMtable
name.
GetMissingReferences
Summary:
Recursiveroutinetoreportallmissingfilereferences.
Parameters:
dmDoc:Parentdocumentofreportedchildren,typicallyanassemblyordrawing.
Remarks:
Reportsbackastringofmissingreferencefilesseparatedbyareturncharacter.

FileOperations
BrowseForFile
GetFilesFromPath
BrowseForFile
Summary:
BrowseforaSOLIDWORKSfileusingtheWindowsOpenFileDialog
ReturnValues:
Returnsthefullpathtotheselectedfile.
GetFilesFromPath
Summary:
Getallfilepathsfromauserselecteddirectory.
Parameters:
extensionFilter:afileextensiontofilter."*.sld*"wouldretrieveallSOLIDWORKSfiles.
includeSubFolders:SettoTruetogetfilesfromallsubfolders
ReturnValues:
Returnsanarrayoffullfilepaths.
Remarks:
Tempfiles,~$Part1.sldprt,shouldbefilteredfromyourresultsbeforeprocessing.

PostedbyMikeSpens

Nocomments:

Recommend this on Google


Labels:API,DocumentManager,SOLIDWORKS

Dec28,2015

CommonVBAProceduresforBatchExport
TryasMicrosoftmay,itdoesntlooklikeVBAisgoingawayanytimesoon!Andreally,
itsagreatplacetostartdevelopingmacrosforSOLIDWORKS.Themacrosaresingle
file,selfcontained,andeasytodevelop.Nottomentionthattherearethousandsof
existingVBAmacrosoutthereandlotsofsamplecodeonline.
Thedownside?VBAdoesnthaveasmanyprebuiltfunctionsforcommonfileoperations
availabletoC#andVB.net.
Inanefforttomakeyourmacrodevelopmenteasier,Iveputtogetherahandfulof
commonroutinesandfunctionsyoucanaddtoyourSOLIDWORKSVBAmacros.If
thereareothersyoudliketosee,letmeknow!

http://www.solidapi.com/

6/11

10/27/2016

SolidAPI
Batchprocessingoffilesisoneofthoseplaceswhereyouneedtomanipulatefile
information.Ratherthanpackingalloftheprocessingintooneroutine,Ihavebrokenit
outintocommonfunctionssoyoucansavethemintoacodemoduletouseinallofyour
macros.

MacroCode
StartbyaddingthefollowingproceduresandfunctionstoyourVBAmacro.

OptionExplicit
DimswAppAsSldWorks.SldWorks
'batchprocessusingDironefolderlevelonly
SubBatchConvert(folderPathAsString,_
fileNameFilterAsString,_
convertExtensionAsString,_
OptionaloutputFolderPathAsString)

DimfileAsString
'useDirfunctiontogetallfilesmatchingthefilter
'inthespecificfolder
file=Dir(folderPath&fileNameFilter)
DoWhileNotfile=""
DimfilePathAsString
filePath=folderPath&file
DimnewFilePathAsString
newFilePath=ConvertSWFile(filePath,convertExtension,_
outputFolderPath)
'getthenextfile
file=Dir
Loop
EndSub
'batchprocessusingFileSystemObjectallsubfoldersincluded
'mustaddareferencetoMicrosoftScriptingRuntimetypelibrary
SubBatchConvert2(folderPathAsString,_
fileNameFilterAsString,_
convertExtensionAsString,_
OptionaldoSubFoldersAsBoolean=False,_
OptionaloutputFolderPathAsString)

DimfileAsString
DimfsoAsNewFileSystemObject
DimfldAsScripting.Folder
Setfld=fso.GetFolder(folderPath)
DimfAsScripting.file
ForEachfInfld.files()
'wildcardsnotallowedinfileNameFilterwhenusing
'FileSystemObjectmethods
IfInStr(1,f.Name,fileNameFilter,_
vbTextCompare)<>0Then
DimnewFilePathAsString
newFilePath=ConvertSWFile(f.Path,_
convertExtension,outputFolderPath)
EndIf
Next
'recursiveroutineifdoSubFoldersisTrue
IfdoSubFoldersThen
DimsubFolderAsScripting.Folder
ForEachsubFolderInfld.subFolders
CallBatchConvert2(subFolder.Path,fileNameFilter,_
convertExtension,doSubFolders,outputFolderPath)
Next
EndIf
EndSub
'openthefileinSOLIDWORKSandconvertbychanging
'thefileextension.newfilewillbecreatedinthe

http://www.solidapi.com/

7/11

10/27/2016

SolidAPI
'samefolderastheparentfile
'or,passanoutputFolderPathstringtosendfilesto
'aspecificfolder
FunctionConvertSWFile(filePathAsString,_
convertExtensionAsString,_
OptionaloutputFolderPathAsString)AsString

DimmodelAsModelDoc2
DimfileTypeAsLong
fileType=GetSWFileType(filePath)
DimerrorsAsLong,warningsAsLong

Setmodel=swApp.OpenDoc6(filePath,_
fileType,swOpenDocOptions_Silent,_
"",errors,warnings)

IfmodelIsNothingThen
ConvertSWFile=""
ExitFunction
EndIf

DimnewFilePathAsString
newFilePath=ChangeExtension(filePath,convertExtension)
IfoutputFolderPath<>""Then
newFilePath=ChangeFolderPath(newFilePath,_
outputFolderPath)
EndIf

Callmodel.Extension.SaveAs(newFilePath,_
swSaveAsCurrentVersion,swSaveAsOptions_Silent,_
Nothing,errors,warnings)

CallswApp.CloseDoc(filePath)

ConvertSWFile=newFilePath
EndFunction

'returnthefiletypefromafullfilepath
'helpfulforopeningvariousSOLIDWORKSfiles
FunctionGetSWFileType(filePathAsString)AsLong
DimextAsString
DimfileTypeAsLong
ext=Right(filePath,Len(filePath)InStrRev(filePath,_
".")+1)
SelectCaseUCase(ext)
Case".SLDPRT"
fileType=swDocPART
Case".SLDASM"
fileType=swDocASSEMBLY
Case".SLDDRW"
fileType=swDocDRAWING
CaseElse
fileType=swDocNONE
EndSelect
GetSWFileType=fileType
EndFunction
'============Filepathmanipulation==================
'changetheextensionofafilefromagivenfilepath
FunctionChangeExtension(filePathAsString,_
newExtensionAsString)AsString
DimfilePathNoExtAsString
filePathNoExt=Left(filePath,InStrRev(filePath,".")1)
ChangeExtension=filePathNoExt&newExtension
EndFunction

http://www.solidapi.com/

8/11

10/27/2016

SolidAPI
'changethefolderpathofthefile
FunctionChangeFolderPath(filePathAsString,_
newFolderPathAsString)AsString
DimfileNameAsString
fileName=Right(filePath,_
Len(filePath)InStrRev(filePath,"\"))
ChangeFolderPath=newFolderPath&fileName
EndFunction
'verifythepathendswith\
FunctionVerifyFolderPath(folderPathAsString)AsString
IfInStrRev(folderPath,"\")<>Len(folderPath)Then
VerifyFolderPath=folderPath&"\"
Else
VerifyFolderPath=folderPath
EndIf
EndFunction
'verifyfolderexists
FunctionVerifyFileFolderExists(fullPathAsString)AsBoolean
DimresAsString
res=Dir(fullPath,vbDirectory)
'resultwillbesomevalueifthefolderexists
Ifres=vbNullStringOrfullPath=""Then
VerifyFileFolderExists=False
Else
VerifyFileFolderExists=True
EndIf
EndFunction
'============Otherutilities===================
'openanyfileinitsassociatedapplication
SubOpenFile(ByValfilePathAsString)
DimWshShellAsObject
SetWshShell=CreateObject("WScript.Shell")
'appendquotesincaseofspacesinfilepath
WshShell.RunChr(34)&filePath&Chr(34)
EndSub

'showafolderbrowserdialogandreturntheselectedfolderpath
'oremptystringifcancelled
FunctionBrowseFolder(messageAsString)AsString
DimfolderBrowserAsObject
DimoptionsAsInteger
options=40'UIwithNewFolderbuttonandrightclickmenus
'options=0'UIwithoutNewFolderbutton
'andnorightclickmenus
SetfolderBrowser=CreateObject("Shell.Application")._
BrowseForFolder(0,message,options)

OnErrorResumeNext
BrowseFolder=folderBrowser.Self.Path
OnErrorGoTo0
EndFunction

Usage
Thefollowingmainproceduremakesuseofmostoftheseproceduresandfunctionsto
publishSOLIDWORKSfilestoPDFinaselecteddirectory.

Submain()
SetswApp=Application.SldWorks

DimfolderPathAsString
'browseforfolder
folderPath=BrowseFolder("Selectfoldertoprocess...")

http://www.solidapi.com/

9/11

10/27/2016

SolidAPI
folderPath=VerifyFolderPath(folderPath)
IfNotVerifyFileFolderExists(folderPath)ThenExitSub
DimconvertExtensionAsString
convertExtension=".PDF"

'ifusingDirfunctiontogetfilesusingwildcards
DimfileNameFilterAsString
fileNameFilter=_
InputBox("Enterthefilenamefilter(*.sldprt,*.sld*):")

DimoutputFolderPathAsString
''optionally,setanoutputfolderpath
'outputFolderPath=_
'BrowseFolder("Selectdestinationfolder...")
'outputFolderPath=VerifyFolderPath(outputFolderPath)
CallBatchConvert(folderPath,fileNameFilter,_
convertExtension,outputFolderPath)

''orifusingFileSystemObjecttoprocessallsubfolders...
'fileNameFilter=_
'InputBox("Enterthefilenamefilter"_
'&"(sldprtor1234.slddrw):")
'CallBatchConvert2(folderPath,fileNameFilter,_
'convertExtension,True)

MsgBox"Finished!"
EndSub

Descriptions
BatchConvertusestheDirfunctiontogetallfilesinagivenfolderandallowswildcards
inthefilenamefilter.Thismethoddoesntsupportprocessingofsubfolders.
BatchConvert2allowsprocessingofsubfolders,butdoesntallowwildcardsbecauseof
itsuseoftheFileSystemObject.Eitherroutinemustbepassedthedesiredconversion
extension,includingtheperiod(.PDFinthisexample).Optionally,youcanpassan
outputfolderpathasafinalargument.Ifanoutputfolderisspecified,allpublishedfiles
gotothatfolder.Ifnooutputfolderpathispassed,thefilesarecreatedinthesame
locationastheirsourcefiles.
ConvertSWFileiscalledforeachfilepath.Thisdoesalltheheavyliftingofopeningthe
fileinSOLIDWORKS,changingthefileextensionandoptionaloutputfolderpath,saving
thenewoutputfileandclosingthesourcefile.Itreturnsthenewlycreatedfilenameif
youneedtologtheresults.

FilePathManipulation
Thereareafewfunctionstohelpwithcommonoperationslikechangingfileextensions,
changingfolderpathsaswellasverifyingafolderpathstringiscompleteandverifyingif
afileorfolderexists.

OtherUtilities
ThelastsectionincludesOpenFile,aroutinetoopenanyfileinitsassociated
application.ThisistriggeringtheWindowsshell,soitisjustlikedoubleclickingonafile
inWindowsExplorer.Itdoesnotreturnaninterfacetotheopenedfileanddoesnotwait
untiltheoperationiscomplete.
BrowseFolderisafunctionthatlaunchesafolderbrowserandreturnstheuserselected
folderpathoranemptystringifcancelled.

Ihopeyoufindthesehelpfulinyournextmacroproject!Letmeknowifthereareothers
youdliketoseeorshare.
PostedbyMikeSpens

Nocomments:

Recommend this on Google


Labels:API,macro,PDF,SOLIDWORKS

http://www.solidapi.com/

10/11

10/27/2016

SolidAPI

Home

OlderPosts

Subscribeto:Posts(Atom)

SolidWorksTechAlerts

SOLIDWORKSVisualize2017SP0.0Documentation
SOLIDWORKS2017SP0isavailablefordownload
SOLIDWORKS2016SP5.0EV(EarlyVisibility)isavailablefordownload
SOLIDWORKS2017PR1isavailablefordownload
SOLIDWORKS2017Beta3isavailablefordownload

Simpletemplate.PoweredbyBlogger.

http://www.solidapi.com/

11/11

You might also like