SOLIDWORKS VBA open drawing of active part - vba

I simply need to open the drawing by using VBA of the active part. Drawing always has the exact same filename and location as the part. What I got is
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swSelMgr As SldWorks.SelectionMgr
Dim swDocSpecification As SldWorks.DocumentSpecification
Dim sName As String
Dim longstatus As Long, longwarnings As Long
Sub main()
Set swApp = Application.SldWorks
Set swDocSpecification = swApp.GetOpenDocSpec("C:\Users\Public\Documents\SOLIDWORKS\SOLIDWORKS
2017\tutorial\AutoCAD\7550-021.slddrw")
sName = swDocSpecification.FileName
swDocSpecification.DocumentType = swDocDRAWING
swDocSpecification.ReadOnly = True
swDocSpecification.Silent = False
Set swModel = swApp.OpenDoc7(swDocSpecification)
longstatus = swDocSpecification.Error
longwarnings = swDocSpecification.Warning
End Sub
But it doesn't work probably because of the file location which may always be different depending on how the active part is named and where the active part is located.
Could someone please share a function to simply open the associated drawing of the part?

Try this:
Option Explicit
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swDraw As SldWorks.ModelDoc2
Dim swDocSpecification As SldWorks.DocumentSpecification
Dim FilePath As String
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
If swModel Is Nothing Then MsgBox "Open an assembly or part": Exit Sub
If swModel.GetType <> swDocumentTypes_e.swDocASSEMBLY And swModel.GetType <> swDocumentTypes_e.swDocPART Then MsgBox "Open an assembly or part": Exit Sub
Set swDocSpecification = swApp.GetOpenDocSpec(swModel.GetPathName)
FilePath = LCase(swModel.GetPathName)
FilePath = Replace(FilePath, ".sldprt", ".slddrw")
FilePath = Replace(FilePath, ".sldasm", ".slddrw")
swDocSpecification.FileName = FilePath
swDocSpecification.DocumentType = swDocumentTypes_e.swDocDRAWING
swDocSpecification.ReadOnly = True
swDocSpecification.Silent = True
Set swDraw = swApp.OpenDoc7(swDocSpecification)
swApp.ActivateDoc3 FilePath, False, swRebuildOnActivation_e.swRebuildActiveDoc, Empty
End Sub

Related

SolidWorks API (VBA) To store String in array

I want to store the dimension name (string) in the form of the array so that I can compare another array (dimension name) to the current.
Public Sub WhateverName
Dim swApp As SldWorks.SldWorks
Dim swModel As ModelDoc2
Dim swPart As PartDoc
Dim swFeat As Feature
Dim swDispDim As DisplayDimension
Dim swDim As Dimension
Dim vDimVals As Variant
Dim swDimInfoNameArr As Variant
Dim SKETCH_NAME As String
Dim i As Variant
Dim swDimName As Variant
Dim swDispDimname As String
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swPart = swModel
SKETCH_NAME = "ISO Standard"
Set swFeat = swPart.FeatureByName(SKETCH_NAME)
Set swDispDim = swFeat.GetFirstDisplayDimension
Do While Not swDispDim Is Nothing
i = 0
'For i = 0 To 4
Set swDim = swDispDim.GetDimension2(Empty)
vDimVals = swDim.GetValue3(swThisConfiguration, Empty)
Debug.Print swDim.Name & "#" & SKETCH_NAME & ": " & Round(vDimVals(0), 6)
Set swDispDim = swFeat.GetNextDisplayDimension(swDispDim)
swDimName = swDim.Name
swDimInfoNameArr(i) = swDimName 'swModel.GetCustomInfoNames2 --> ERROR
i = i + 1
'Next
Loop
End Sub
27th line is throwing the error "Type Mismatch"
You need to declare the size of the array, or use an other object to store. Like a dictionnary:
Option Explicit
Sub main()
Dim swApp As SldWorks.SldWorks
Dim swModel As ModelDoc2
Dim swPart As PartDoc
Dim swFeat As Feature
Dim swDispDim As DisplayDimension
Dim swDim As Dimension
Dim vDimVals As Variant
Dim SKETCH_NAME As String
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swPart = swModel
SKETCH_NAME = "ISO Standard"
Set swFeat = swPart.FeatureByName(SKETCH_NAME)
Set swDispDim = swFeat.GetFirstDisplayDimension
Do While Not swDispDim Is Nothing
Set swDim = swDispDim.GetDimension2(Empty)
vDimVals = swDim.GetValue3(swThisConfiguration, Empty)
Set swDispDim = swFeat.GetNextDisplayDimension(swDispDim)
dict.Add swDim.Name, Round(vDimVals(0), 6)
Debug.Print dict.keys()(dict.Count - 1) & "#" & SKETCH_NAME & ": " & dict.Items()(dict.Count - 1)
Loop
End Sub

VBA (API) save SOLIDWORKS drawing as PDF in a set location

I am trying to figure out how to modify my PDF saving macro so that instead of saving the PDF in the same folder as drawing, it would save it to a set location that's written out in macro.
The code I am working with is:
Sub Save_PDF()
'Declare variables
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swExportPDFData As SldWorks.ExportPdfData
Dim strFilename As String
Dim status As Boolean
Dim errors As Long, warnings As Long
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
'Export to PDF if it is a drawing
If (swModel.GetType = swDocDRAWING) Then
strFilename = swModel.GetPathName
strFilename = Left(strFilename, Len(strFilename) - 6) & "pdf"
Set swExportPDFData = swApp.GetExportFileData(1)
swModel.Extension.SaveAs strFilename, 0, 0, swExportPDFData, 0, 0
End If
End Sub
Would someone, please, help me with this one?
You just need to get the name of the file then concatenate with the rest of the path, and remove the unnecessary lines, like this:
Option Explicit
Sub Save_PDF()
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim strFilename As String
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
If swModel.GetType <> swDocDRAWING Then MsgBox ("Error: Not a drawing"): Exit Sub
strFilename = swModel.GetPathName
strFilename = "G:\45 Design\" & Mid(strFilename, InStrRev(strFilename, "\") + 1, InStrRev(strFilename, ".") - InStrRev(strFilename, "\")) & "pdf"
MsgBox "Save path : " & strFilename
swModel.Extension.SaveAs strFilename, 0, 0, Nothing, 0, 0
End Sub

Updating method of batch conversion of .doc files to .txt

I am trying to create an application that will batch convert .doc files to .txt. I have suggested code, that I've modified to take care of errors, but it still Not pulling up the broswer box (allowing a directory to be selected).
Module Module1
Sub ConvertDocumentsToTxt()
'Updated by Extendoffice 20181123
Dim xIndex As Long
Dim xFolder As Object
Dim xFileStr As String
Dim xFilePath As String
Dim xDlg As FileDialog
Dim xActPath As String
Dim xDoc As XDocument
Dim ScreenUpdating As Boolean
ScreenUpdating = False
xDlg = FileDialog(msoFileDialogFolderPicker)
If xDlg.ShowDialog <> -1 Then Exit Sub
xFolder = SelectedItems(1)
xFileStr = Dir(xFolder & "\*.doc")
Dim ActiveDocument As Object = Nothing
xActPath = ActiveDocument.Path
While xFileStr <> ""
xFilePath = xFolder & "\" & xFileStr
If xFilePath <> xActPath Then
Dim Documents As Object = Nothing
xDoc = Documents.Open(xFilePath, AddToRecentFiles:=False, Visible:=False)
xIndex = InStrRev(xFilePath, ".")
Debug.Print(Left(xFilePath, xIndex - 1) & ".txt")
Dim wdFormatText As Object = Nothing
SaveFileDialog(Left(xFilePath, xIndex - 1) & ".txt", FileFormat:=wdFormatText, AddToRecentFiles:=False)
End If
End While
xFileStr = Dir()
ScreenUpdating = True
End Sub
Private Sub SaveFileDialog(v As String, FileFormat As Object, AddToRecentFiles As Boolean)
Throw New NotImplementedException()
End Sub
Private ReadOnly Property SelectedItems(v As Integer) As Object
Get
Throw New NotImplementedException()
End Get
End Property
Private ReadOnly Property FileDialog(msoFileDialogFolderPicker As Object) As FileDialog
Get
Throw New NotImplementedException()
End Get
End Property
Public Property msoFileDialogFolderPicker As Object
End Module

Add-in that adds code to new Excel Workbooks

I'm trying to change my add-in so that it, when you would open a new Workbook, will open a new Sheet and then create a new Event Procedure in that new Sheet.
I've gotten to the point where I can "Sheets.Add" and ".CreateEventProc" using a macro button combination, but the issue comes when trying to use the add-in's Workbook to automate the process. The add-in loads in first, thus "Set VBProj = ActiveWorkbook.VBProject" can't find the new active workbook.
Is it possible to do this? If so, is there a work around needed or am I just missing something obvious?
Here's what I have at the moment:
Option Explicit
Private WithEvents App As Excel.Application
Private Sub Workbook_Open()
Set App = Excel.Application
End Sub
Private Sub App_NewWorkbook(ByVal Wb As Workbook)
Range("T2").Value = 100
ActiveWorkbook.Sheets.Add
Call CreateEventProcedure
End Sub
Public Sub CreateEventProcedure()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim NumLines As Long
Dim LineNum As Long
Dim ProcName As String
Dim ProcKind As VBIDE.vbext_ProcKind
Const DQUOTE = """" ' one " character
Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents("Sheet2")
Set CodeMod = VBComp.CodeModule
With CodeMod
LineNum = .CountOfDeclarationLines + 1
Do Until LineNum >= .CountOfLines Or ProcName = "Worksheet_Change"
ProcName = .ProcOfLine(LineNum, ProcKind)
LineNum = .ProcStartLine(ProcName, ProcKind) + _
.ProcCountLines(ProcName, ProcKind) + 1
Loop
If ProcName = "Worksheet_Change"
GoTo Exi
End If
'Now, create a Change Event on Sheet2
LineNum = .CreateEventProc("Change", "Worksheet")
For those who care, I got the process working with a minor complication. Here's what I did:
Option Explicit
Private WithEvents ExApp As Excel.Application
Public Sub ExApp_WorkbookOpen(ByVal Wb As Workbook)
Dim StrPrompt As String
Dim strTitle As String
Dim iRet As Integer
StrPrompt = "Want to create event?"
strTitle = "Event?"
On Error GoTo 0
iRet = MsgBox(StrPrompt, vbYesNo, strTitle)
If iRet = vbYes Then
ActiveWorkbook.Sheets.Add
Call CreateEventProcedure
End If
On Error GoTo 0
ActiveWorkbook.Sheets.Add
Call CreateEventProcedure
End If
End Sub
Private Sub Workbook_Open()
Set ExApp = Excel.Application
End Sub
I created the Yes/No prompt to Bypass the first 'run-time _Global' error and then the excel workbook actually loads, the prompt asks me again then I click yes and everything works fine. Also, this works with only one prompt needed when opening workbooks when already in excel.

Object Required VBA Outlook

I'm not sure what it doesn't like about my code here, I'm experienced in .NET, but VBA is new to me. I know when called functions not to do myFunction('args') and do myFunction args instead, but I don't have that issue here. Any help is appreciated. THanks!
Public Sub LogMeIn()
Dim item As Outlook.MailItem
Dim body As String
Dim subject As String
Dim oFld As Outlook.Folder
Dim oNS As Outlook.NameSpace
Dim oMails As Outlook.items
Dim oProp As Outlook.PropertyPage
Dim mySelection As Word.Selection
Dim strItem As String
Dim omailitem As Variant
Set oNS = Application.GetNamespace("MAPI")
Set oFld = oNS.GetDefaultFolder(olFolderInbox)
Set oMails = oFld.items
For Each omailitem In oMails
Set body = omailitem.body
Set subject = omailitem.subject
Dim pos As Integer
Set pos = 0
Dim copyText As String
If InStr(omailitem.subject, "Your LogMeIn Security Code:") > 0 Then
Set copystr = Mid(omailitem.body, pos + 28, 9)
Dim dataToSave As New DataObject
dataToSave.SetText copystr
dataToSave.putinclipboard
'MsgBox ("subject true")
End If
'MsgBox ("subject true")
'If omailitem.subject.Find("Your LogMeIn Security Code:") Then
'MsgBox ("subject true")
'End If
Next
End Sub
Private Sub Application_NewMail()
Call LogMeIn
End Sub
You try to assign object reference to data type. String is a data type in VBA and not an object. The keyword Set is used with object. Remove this keyword when it's data type or you will get an error.
Dim body As String
Dim subject As String
Set body = omailitem.body
Set subject = omailitem.subject
Dim pos As Integer
Set pos = 0
[...]