Macro - create model window from open drawing

Purpose:

  • Save open Drawing file as PDF (complete)
  • Show user list of "open" referenced documents (complete)
  • Have user select from list on userform (complete)
  • Switch to (or create) model window of selected document.
  • Save Selected document as eDrawing (complete) 

So the only Open file or Document window I have open is my drawing.  I have tried using the swApp.OpenDoc6 call as shown in the numerous Open file macros on the forum.  However I get the following error:
swFileLoadError_e Enumeration

swFileWithSameTitleAlreadyOpen65536 or 0x10000 = A document with the same name is already open

When I call swFrame.GetModelWindowCount I am informed that I only have 1 model window active.

So my question is this: How do I get a new model window for a file that is referenced by an open document?

Thanks in advance for all your head scratching.

SolidworksApi/macros
Answers 20
JB
JB 2021-04-08 Best Answer

Excerpt from the API help on OpenDoc6:

ISldWorks::OpenDoc6 does not activate and display the document if the file is already open in memory in an assembly or drawing. However, ISldWorks::OpenDoc6 should return a valid IModelDoc2 pointer that is usable with functions that do not require a document to be displayed. If you want, ISldWorks::ActivateDoc2 or ISldWorks::IActivateDoc3 will activate and display the document. Because calling ISldWorks::OpenDoc6 does not activate nor display the file, calling the ISldWorks::ActiveDoc or ISldWorks::IActiveDoc2 property will not return a pointer to this document.

AM
AM 2021-04-08

Yup Moderation cause my question to lag over the weekend.  I did get it resolved...  I'm just honestly not sure what it was that I did that fixed it....

AT
AT 2021-04-08

Sorry, Arthur, not sure if you have the issue resolved. I believe due to moderation it all got messed up. Please let me know if you have any outstanding issues.

AM
AM 2021-04-08

So... After messing with the code extensively.... I can't get it to break anymore, and I'm not sure what it was that I did to fix it.

I took the code from the CodeStack Macro and overwrote a bunch of my failing to fix it code.  I can't figure out what it is that is different than what I had though.

Working macro attached.

AM
AM 2021-04-08

Bring document foreground (activate document) using SOLIDWORKS API 

Found this Macro on Codestack, going to see if going through it will help me get this figured out.

AM
AM 2021-04-08

Asked a question of Artem but it's waiting in moderator limbo

AM
AM 2021-04-08

Thanks ‌ how would I change the code so that I could give it a file name instead of a View.ReferencedDoc?

AT
AT 2021-04-08

Ok, so it works, right? I believe you might have opened the drawing in lightweight mode so it took some time to load an assembly. You should have similar performance when doing manual activation as well. If you restart SW (as it is not cached in memory and will be instant).

AM
AM 2021-04-08

So ‌, I downloaded the code, ran it line by line till it got to: swDoc.Visible = True  then Sw froze for 7 minutes.

edit:  While typing this message SW finally loaded the assembly.

AT
AT 2021-04-08

Try attached macro on your model. Does it work?

AM
AM 2021-04-08

‌ & ‌, if the following part of code makes no sense that's cause it's me messing around trying to figure out what to do.

If swModel Is Nothing Then
swApp.CreateNewWindow
swModel = swApp.ActivateDoc3(ChosenDoc, False, swRebuildOnActivation_e.swRebuildActiveDoc, fileerror)

Debug.Print " Error (0 = no errors) = " & fileerror


'If Not swModel.Visible Then

modelWindows = swFrame.modelWindows
For Each obj In modelWindows
'Get the model document in this model window
Set swModel = swModelWindow.ModelDoc
'Rebuild the document
swModel.EditRebuild3
Set swModel = Nothing
'Show the model window
Debug.Print ""
swFrame.ShowModelWindow swModelWindow
'Get and print the model window handle
hWnd = swModelWindow.hWnd
Debug.Print (" Model window handle: " & hWnd)
'Get and print the model title as it is seen in the model window's title bar
Debug.Print (" Model title as it seen in the model's window's title bar: " & swModelWindow.Title)

Next obj
Debug.Print swFrame.GetMenu

swFrame.IGetModelWindows (0)
'swModel.Visible = True
'End If
End If

Stop

AM
AM 2021-04-08

Attached module & settings text.

DG
DG 2021-04-08

Can you please attach/share the SWP file? 

AM
AM 2021-04-08

So I have discovered where my code fails more closely. (Calls within userform "trimmed down" for clarity)

Dim Filter As String
Dim fileConfig As String
Dim fileDispName As String
Dim fileOptions As Long

'strFolder = BrowseFolder(Caption:="Select A Folder/Path", InitialFolder:=Txt_FolderPath.Value)

'note the use of the | character between filters
Filter = "All SOLIDWORKS Files (*.sldprt; *.sldasm; *.slddrw)|*.sldprt;*.sldasm;*.slddrw|SOLIDWORKS Model Files (*.sldprt; *.sldasm)|*.sldprt;*.sldasm|" & _
"SOLIDWORKS Drawing Files (*.slddrw)|*.slddrw|All Files (*.*)|*.*|"

strBrowseFile = swApp.GetOpenFileName("Select File", Txt_FolderPath.Value, Filter, fileOptions, fileConfig, fileDispName)

If Not strBrowseFile = "" Then
Debug.Print "File Name: " & strBrowseFile

strFolder = Left(strBrowseFile, InStrRev(strBrowseFile, "\"))
Debug.Print "Folder path: " & strFolder

Txt_FolderPath.Value = strFolder
ChosenDoc = strBrowseFile

Dim docType As Long


If Not Pre_select Then
ChosenDoc = Option_Selected

If IsEmpty(ChosenDoc) Then
Exit Sub
End If

End If

sFileType = Right(ChosenDoc, 7)
Select Case LCase(sFileType)
Case ".slddrw"
docType = 3
Case ".sldprt"
docType = 1
Case ".sldasm"
docType = 2
Case Else
MsgBox "Error: " & sFileType & vbNewLine & "File type not set up.", vbCritical
Exit Sub
End Select

If BoolDebug Then
Debug.Print "Current working directory is " & swApp.GetCurrentWorkingDirectory
End If

sFileName = Right(ChosenDoc, Len(ChosenDoc) - InStrRev(ChosenDoc, "\"))
swApp.SetCurrentWorkingDirectory (Left(ChosenDoc, Len(ChosenDoc) - Len(sFileName)))


sFrame(1) = "Please, be patient while macro is working."


If BoolModal Then
' modal to non-modal
Me.Hide
Me.show vbModeless
BoolModal = False
'Debug.Print "Modal State: " & ShowModal; Property
End If

swFrame.SetStatusBarText sFrame(1) ' feed status message to status bar

Set swModel = swApp.GetOpenDocumentByName(ChosenDoc)

the next if statement is where the problem arises. If the previous Set swModel = swApp.GetOpenDocumentByName(ChosenDoc) is a "Nothing" it enters this if logic that keeps failing.

If swModel Is Nothing Then
swApp.CreateNewWindow
swModel = swApp.IActivateDoc3(ChosenDoc, False, fileerror)
AM
AM 2021-04-08

Problem area:

Private Sub Confirm_Click(Optional Pre_select As Boolean = False)

Dim docType As Long


If Not Pre_select Then
ChosenDoc = Option_Selected

If IsEmpty(ChosenDoc) Then
Exit Sub
End If

End If

sFileType = Right(ChosenDoc, 7)
Select Case LCase(sFileType)
Case ".slddrw"
docType = 3
Case ".sldprt"
docType = 1
Case ".sldasm"
docType = 2
Case Else
MsgBox "Error: " & sFileType & vbNewLine & "File type not set up.", vbCritical
Exit Sub
End Select

If BoolDebug Then
Debug.Print "Current working directory is " & swApp.GetCurrentWorkingDirectory
End If

sFileName = Right(ChosenDoc, Len(ChosenDoc) - InStrRev(ChosenDoc, "\"))
swApp.SetCurrentWorkingDirectory (Left(ChosenDoc, Len(ChosenDoc) - Len(sFileName)))


sFrame(1) = "Please, be patient while macro is working."


If BoolModal Then
' modal to non-modal
Me.Hide
Me.show vbModeless
BoolModal = False
'Debug.Print "Modal State: " & ShowModal; Property
End If

swFrame.SetStatusBarText sFrame(1) ' feed status message to status bar

Set swModel = swApp.GetOpenDocumentByName(ChosenDoc)

Debug.Assert Not BoolDebug
If swModel Is Nothing Then
swApp.CreateNewWindow
swModel = swApp.ActivateDoc3(ChosenDoc, False, swRebuildOnActivation_e.swRebuildActiveDoc, fileerror)

If I try this with OpenDoc6 I get the fileerror as: 

swFileWithSameTitleAlreadyOpen65536

I tried with IActivateDoc3 but I can't seem to get the arguments set up correctly to use it.

When I use ActivateDoc3 I get a "With variable not set up".

ChosenDon is filled by this code:

Private Sub Cmb_Browse_Click()

Dim Filter As String
Dim fileConfig As String
Dim fileDispName As String
Dim fileOptions As Long

'strFolder = BrowseFolder(Caption:="Select A Folder/Path", InitialFolder:=Txt_FolderPath.Value)

'note the use of the | character between filters
Filter = "All SOLIDWORKS Files (*.sldprt; *.sldasm; *.slddrw)|*.sldprt;*.sldasm;*.slddrw|SOLIDWORKS Model Files (*.sldprt; *.sldasm)|*.sldprt;*.sldasm|" & _
"SOLIDWORKS Drawing Files (*.slddrw)|*.slddrw|All Files (*.*)|*.*|"

strBrowseFile = swApp.GetOpenFileName("Select File", Txt_FolderPath.Value, Filter, fileOptions, fileConfig, fileDispName)

If Not strBrowseFile = "" Then
Debug.Print "File Name: " & strBrowseFile

strFolder = Left(strBrowseFile, InStrRev(strBrowseFile, "\"))
Debug.Print "Folder path: " & strFolder

Txt_FolderPath.Value = strFolder
ChosenDoc = strBrowseFile
End If: End Sub

AM
AM 2021-04-08

Since Deepak asked for all the code... Here is the monstrosity.

The part I'm having a problem with will be isolated in my reply to this.

Main module:

' ******************************************************************************
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swDoc As SldWorks.ModelDoc2
Dim swModelDocExt As SldWorks.ModelDocExtension
Dim swCustProp As CustomPropertyManager
Dim swFrame As SldWorks.Frame

Dim boolstatus(0 To 5) As Boolean
Public BoolDebug As Boolean, BoolFrm As Boolean
Dim longstatus As Long, longwarnings As Long
Dim iReply, sFrame(0 To 1) As String
Dim Prop_N() As String
Public saveDir As String
Dim FileDir As String, sDrive(0 To 1) As String, FileName As String, sRev As String, sP_Numb As String, sStatus As String
Dim FileExt(0 To 4) As String
Dim FileChk As Boolean
Public Settings() As String
Dim fdObj As Object

Private Const GWL_STYLE = -16
Private Const WS_CAPTION = &HC00000
Private Const WS_SYSMENU = &H80000
Private Declare PtrSafe Function GetWindowLong _
Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, _
ByVal nIndex As Long) As Long
Private Declare PtrSafe Function SetWindowLong _
Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, _
ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Declare PtrSafe Function FindWindowA _
Lib "user32" (ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long
Private Declare PtrSafe Function DrawMenuBar _
Lib "user32" (ByVal hWnd As Long) As Long

'-----------------------------------------------------------------------------------'
Sub Main()

Set swApp = Application.SldWorks
Set swFrame = swApp.Frame ' set status bar variable
Set swDoc = swApp.ActiveDoc
'check that a File is open
If swDoc Is Nothing Then
iReply = "No File open"
MsgBox iReply
End
End If

Set swModelDocExt = swDoc.Extension
Set swCustProp = swModelDocExt.CustomPropertyManager("")
'


' Bring in the Custom Properties from the file.
Prop_N() = Split("Status, PROJECT NO, Revision, CheckedBy, Description", ", ")
'
' Debug toggle for testing, exits certain loops
BoolDebug = True
If BoolDebug Then
iReply = "WARNING! Macro under development"
MsgBox iReply
End If
'*************

Dim swSnapShot As SnapShot
Set swSnapShot = swDoc.ModelViewManager.AddSnapShot("Home")
'**************

'Gets current file name and path
FileName = swDoc.GetPathName
Debug.Print vbCrLf & "Solidworks Publish Macro being run for file:" & vbNewLine & FileName

'Checks to make sure current file is a drawing
If swDoc.GetType <> swDocDRAWING Then
FrmDrwChk.show
'sRev = 0
Else
Dim I As Integer
Dim val As String, valout As String
For I = 0 To UBound(Prop_N)
boolstatus(I) = swCustProp.Get4(Prop_N(I), False, val, valout)
'Debug.Print "Value: " & val
'Debug.Print "Evaluated value: " & valout
'Debug.Print "Up-to-date data: " & boolstatus(i)
Select Case I
Case 0
sStatus = valout
Case 1
sP_Numb = valout
Case 2
sRev = valout
Case 3
If valout = " " Or valout = "" Or UCase(valout) = "XX" Then
FileChk = False
Else
If BoolDebug Then Debug.Print "Checked by: " & valout
FileChk = True
End If
Case 4
Debug.Print "Description: " & valout
Case Else
MsgBox "Unrecognized Property"
Exit Sub
End Select
Next I
End If


' Settings for save location
ReDim Settings(0)
'Publish-Settings.txt
'.txt file location:
Settings(0) = "M:\Drafting\03-TOOLBOX\05-SW Config\"

'test file location
If BoolDebug Then
Settings(0) = "\\ss-yxc01-wfs01.selkirksigns.local\Cranbrook\Departments\Drafting\01-SANDBOX\02_AM\SW Macro"
End If

'*************************************************************************************************
Settings = SettingsRead(Settings(0))


'get existing file extension
FileExt(0) = Right(FileName, 7)

'set up save file extensions
FileExt(1) = ".PDF"
FileExt(2) = ".EDRW"
FileExt(3) = ".EASM"
FileExt(4) = ".EPRT"

'strips solidworks extension off name and replaces with pdf
' file extension: .slddrw -> 7 char
FileDir = Left(FileName, Len(FileName) - 7)

'********************************
'GETUNC function
sDrive(0) = Left(FileDir, 2)
If Right(sDrive(0), 1) <> "\" Then
sDrive(1) = GetUNC(sDrive(0))

FileDir = Right(FileDir, Len(FileDir) - 2)
FileDir = sDrive(1) & FileDir
Else
sDrive(1) = sDrive(0)
End If


' Folder Tree check
For I = 0 To UBound(Settings, 2)

If BoolDebug Then
MsgBox FileDir & vbCrLf & Left(Settings(0, I), InStrRev(Settings(0, I), "\") - 1) & vbCrLf & _
InStr(LCase(FileDir), LCase(Left(Settings(0, I), InStrRev(Settings(0, I), "\") - 1)))
Debug.Assert Not (BoolDebug)
End If

boolstatus(I) = False
Select Case True
Case Settings(0, I) = "" And Not I = UBound(Settings, 2)
Case InStr(1, LCase(FileDir), LCase(Left(Settings(0, I), InStrRev(Settings(0, I), "\") - 1)), 1) > 0 _
And Not Settings(0, I) = ""
saveDir = Left(FileDir, InStr(LCase(FileDir), LCase(Left(Settings(0, I), InStrRev(Settings(0, I), "\")))) - 1) & Settings(0, I)
boolstatus(I) = FolderChk(saveDir, "Published\")

Case I = UBound(Settings, 2) And saveDir = ""
saveDir = Left(FileDir, InStrRev(FileDir, "\"))
boolstatus(I) = FolderChk(saveDir, "Published\")

End Select

Next I

'Save to Directory
If InStr(LCase(Right(saveDir, 11)), "published") = 0 Then
saveDir = saveDir & "Published\"
End If
If Right(saveDir, 1) <> "\" Then
saveDir = saveDir & "\"
End If
' If expected publish folder does not exist create it
If boolstatus(0) = False And boolstatus(1) = False Then
fdObj.CreateFolder (Left(saveDir, Len(saveDir) - 1))
End If

' If Right(saveDir, 1) <> "\" Then
' saveDir = saveDir & "\"
' End If

FileName = Right(FileDir, Len(FileDir) - InStrRev(FileDir, "\"))
'**********************************************


'Revison format
If sRev = CStr("0") Or sRev = "" Then
sRev = ""
Else
sRev = "_R" & sRev
End If

'Project Number Format
sP_Numb = UCase(sP_Numb)

If InStr(sP_Numb, " ") > 0 Then
sP_Numb = Left(sP_Numb, InStr(sP_Numb, " ") - 1)
End If
If IsNumeric(Mid(sP_Numb, 4, 4)) = True Then

If InStr(UCase(FileName), sP_Numb) = 0 Then
FileName = sP_Numb & "_" & FileName
End If
Else
sP_Numb = ""
End If

' Status Property Upper case
sStatus = UCase(sStatus)

'save loop
For I = 1 To 2

' Status & Save Directory Copied to clipboard
CopyTextToClipboard (sStatus & vbNewLine & saveDir)
If BoolDebug Then
Debug.Print sStatus & vbNewLine & saveDir
End If

If I = 1 Then
' File checked Msg
If sStatus = "FOR FAB" And FileChk <> True Then
MsgBox "File not checked."
End If

Else
If sStatus <> "FOR FAB" Then Exit For

' If MsgBox("Use macro eDrawing save function?", vbYesNo, "eDrawing Save") = vbNo Then
'
' CopyTextToClipboard (fileName & sRev & FileExt(I))
' MsgBox "File name: " & fileName & sRev & FileExt(I) & vbCrLf & "copied to clipboard"
' Exit For
' End If

'** Solidworks Status Frame text
Dim BaseVersion As String, CurrentVersion As String, HotFixes As String

swApp.GetBuildNumbers2 BaseVersion, CurrentVersion, HotFixes
' Debug.Print "SOLIDWORKS major revision number: " & BaseVersion
' Debug.Print "SOLIDWORKS build number: " & CurrentVersion
' Debug.Print "SOLIDWORKS hot fix numbers: " & HotFixes
sFrame(0) = "SolidWorks " & Mid(BaseVersion, 3, 4) & " Service Pack " & Mid(BaseVersion, InStr(BaseVersion, "SP") + 2, 2) & "." & _
IIf(Len(BaseVersion) <= InStr(BaseVersion, "SP") + 4, "0", Mid(BaseVersion, InStr(BaseVersion, "SP") + 4))

'** EASM or EPRT SELECTION
With Frm_eDraw_file_choose
.saveDir = Left(saveDir, Len(saveDir) - Len("\Published\"))
.SaveName = FileName & sRev
.show
End With
While BoolFrm
DoEvents: Wend

swFrame.SetStatusBarText sFrame(0) ' feed status message to status bar

End If

If swApp.ActiveDoc.GetType <> 3 Then '1 = part, 2 = assembly, 3 = drawing
Select Case swApp.ActiveDoc.GetType
Case 1
I = 4
Case 2
I = 3
Case Else
MsgBox "File type error!", vbCritical
End
End Select: End If

' Saving the File
boolstatus(I) = FileSave(saveDir, FileName, sRev, FileExt(I))

'Save status message
If Not boolstatus(I) Then
MsgBox "Problem Saving " & FileExt(I) & " File"
Debug.Print "Problem Saving " & FileExt(I) & " File"
Else
MsgBox FileExt(I) & " File Saved"
Debug.Print FileExt(I) & " File Saved"
End If

Next I


'**** 00-Publish folder system and check system ------------------------
Debug.Assert Not BoolDebug
If sStatus <> "FOR REVIEW" Then
If InStr(LCase(saveDir), LCase(Left(Settings(0, 1), Len(Settings(0, 1)) - 1))) > 0 Then

For I = LBound(Settings(), 2) To UBound(Settings(), 2)
boolstatus(I) = FolderChk(Left(saveDir, Len(saveDir) - Len(Settings(0, 1)) - Len("Published\")), Settings(1, I))

If Not boolstatus(I) Then

Debug.Print Len(Settings(0, I)) & " - " & Len(Replace(Settings(0, I), "\", ""))
Stop
Debug.Print InStrRev(Settings(1, I), "\", Len(Settings(1, I)) - 2)
'~*~*~*~*~~*~*~ problem here
If (Len(Settings(0, I)) - Len(Replace(Settings(0, I), "\", ""))) > 1 Then
If Not FolderChk(Left(saveDir, Len(saveDir) - Len(Settings(0, 1)) - Len("Published\")), _
Left(Settings(1, I), Len(Settings(1, I)) - InStrRev(Settings(1, I), "\", Len(Settings(1, I)) - 2))) Then
fdObj.CreateFolder Left(saveDir, Len(saveDir) - Len(Settings(0, 1)) - Len("Published\")) _
& Left(Settings(1, I), Len(Settings(1, I)) - InStrRev(Settings(1, I), "\", Len(Settings(1, I)) - 2)): End If
End If

fdObj.CreateFolder Left(saveDir, Len(saveDir) - Len(Settings(0, 1)) - Len("Published\")) _
& Left(Settings(1, I), Len(Settings(1, I)) - 1)
End If

Next I
Frm_FoldersOpen.show
Else
iReply = Settings(1, 0) & "Folder tree not properly set up"
Debug.Print iReply
MsgBox (iReply)
End If
End If

If sStatus = "FOR FAB" Then
MsgBox "Don't forget to export any CNC files"
End If
End Sub


Function FileSave(DIR As String, NAME As String, REV As String, EXT As String) As Boolean

If InStr(UCase(EXT), "E") > 0 Then
' edrawing options: swEdrawingSaveActive, swEdrawingSaveAll, swEdrawingSaveSelected
Application.SldWorks.SetUserPreferenceIntegerValue swEdrawingsSaveAsSelectionOption, swEdrawingSaveAll
End If
FileSave = Application.SldWorks.ActiveDoc.Extension.SaveAs(DIR & NAME & REV & EXT, swSaveAsCurrentVersion, swSaveAsOptions_Silent, Nothing, longstatus, longwarnings)
'Debug.Print "Error: " & longstatus & vbNewLine & "Warning: " & longwarnings
End Function


Function FolderChk(sPath As String, sTarget As String) As Boolean

Dim iTemp As Integer
Dim DirExists As Boolean


'Application.ScreenUpdating = False
Set fdObj = CreateObject("Scripting.FileSystemObject")

If InStr(sPath, sTarget) = 0 Then
If Right(sPath, 1) <> "\" Then
sPath = sPath & "\"
End If
sPath = sPath & sTarget
End If

If Right(sPath, 1) = "\" Then
sPath = Left(sPath, Len(sPath) - 1)
End If

If fdObj.FolderExists(sPath) Then

FolderChk = True
Exit Function: End If

'Application.ScreenUpdating = True

End Function

Function IsFile(ByVal fName As String) As Boolean
'Returns TRUE if the provided name points to an existing file.
'Returns FALSE if not existing, or if it's a folder
On Error Resume Next
IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory)
End Function


Function SettingsRead(sPath As String) As String()

Dim Delimiter() As String
Dim FileName As String
Dim TextFile As Integer
Dim FileContent As String
Dim LineArray() As String
Dim DataArray() As String
Dim TempArray() As String
Dim tempstr As String
Dim BoolArray As Boolean
Dim rw As Long, col As Long
Dim ArrSize() As String

'Inputs
Delimiter() = Split("}, : , ;", ", ")
FileName = "Publish-Settings.txt"
rw = 0

'Open the text file in a Read State
TextFile = FreeFile
Open sPath & "\" & FileName For Input As TextFile

'Store file content inside a variable
FileContent = Input(LOF(TextFile), TextFile)

'Close Text File
Close TextFile

'Debug.Print "Settings Len: "; Len(FileContent)

'Remove commented text
Do While InStr(FileContent, vbCrLf & "'") > 0

tempstr = Mid(FileContent, InStr(FileContent, vbCrLf & "'"), _
InStr(InStr(FileContent, vbCrLf & "'") + 1, FileContent, vbCrLf) - InStr(FileContent, vbCrLf & "'"))

FileContent = Replace(FileContent, tempstr, "")

Loop

FileContent = Replace(FileContent, " }", "")

'Separate Out lines of data
LineArray() = Split(FileContent, vbCrLf)

ArrSize() = Split(LineArray(0), ";")
ArrSize(0) = Right(ArrSize(0), 1)
ReDim DataArray(ArrSize(0) - 1, ArrSize(1) - 1)

'Read Data into an Array Variable
Dim I As Integer, j As Integer, X As Integer, Y As Integer
j = 0
For X = 0 To UBound(LineArray)

' tempSTR = LineArray(X)
'Check Settings set up proper
Select Case True
Case LineArray(X) = "" Or tempstr = " "
'empty array entity
Case InStr(1, LineArray(X), "Array", 1)
' Array size config
Case InStr(1, LineArray(X), "UNC", 1)
BoolArray = True
Case InStr(1, LineArray(X), "Publish ")
BoolArray = True
Case Else
iReply = "Unrecognized Property in Settings File" & vbCrLf & "Check Settings or Macro"
MsgBox iReply
End Select

If BoolArray Then
TempArray = Split(Mid(LineArray(X), InStr(LineArray(X), Delimiter(1)) + 1), Delimiter(2))

For Y = 0 To UBound(TempArray)
DataArray(j, Y) = Trim(TempArray(Y))
Next Y
j = j + 1
BoolArray = False
End If

Next X

SettingsRead = DataArray()

End Function

Function GetUNC(strMappedDrive As String) As String
Dim objFso As FileSystemObject
Set objFso = New FileSystemObject
Dim strDrive As String
Dim strShare As String
'Separated the mapped letter from any following sub-folders
strDrive = objFso.GetDriveName(strMappedDrive)

'find the UNC share name from the mapped letter
strShare = objFso.Drives(strDrive).ShareName

'The Replace function allows for sub-folders of the mapped drive
GetUNC = Replace(strMappedDrive, strDrive, strShare)

Set objFso = Nothing 'Destroy the object
End Function

Sub CopyTextToClipboard(txt_String As String)
'PURPOSE: Copy a given text to the clipboard (using DataObject)
'NOTES: Must enable Forms Library: Checkmark Tools > References > Microsoft Forms 2.0 Object Library

Dim obj As New DataObject


'Make object's text equal above string variable
obj.SetText txt_String

'Place DataObject's text into the Clipboard
obj.PutInClipboard

'Notify User
' MsgBox "There is now text copied to your clipboard!", vbInformation

Set obj = Nothing

End Sub

Sub ShowFolder(sPath As String)
Shell "cmd.exe /c start """" """ & sPath & """", vbNormalFocus
End Sub

Public Sub SystemButtonSettings(frm As Object, show As Boolean)
Dim windowStyle As Long
Dim windowHandle As Long

windowHandle = FindWindowA(vbNullString, frm.Caption)
windowStyle = GetWindowLong(windowHandle, GWL_STYLE)

If show = False Then

SetWindowLong windowHandle, GWL_STYLE, (windowStyle And Not WS_SYSMENU)

Else

SetWindowLong windowHandle, GWL_STYLE, (windowStyle + WS_SYSMENU)

End If

DrawMenuBar (windowHandle)

End Sub

Form1: FrmDrwChk

Private Sub btnCancel_Click()
Unload Me
End
End Sub

Private Sub btnConfrirm_Click()
Unload Me
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 0 Then
Unload Me
End
End If
End Sub

Form2:Frm_eDraw_file_choose

Option Explicit
Dim A, b, ab, c As Integer
Dim FilesOpen As Variant
Dim FolderFiles() As String
Dim optBtn() As msforms.OptionButton
Dim intFileOp As Integer, Incr_H As Double, Incr_W As Double, Frm_H() As Double, Frm_W() As Double, Max_Incr As Integer
Dim strFileName, strFolder, strFileSpec, sFileType As String, sFileName As String, f_saveDir As String, f_SaveName As String, sTemp As String
Dim strBrowseFile As String
Dim intFoundFiles As Integer
Dim BoolModal As Boolean, BoolBrowse As Boolean
Private collect_optBtn1 As New Collection
Private collect_optBtn2 As New Collection
Dim WithEvents swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swFrame As SldWorks.Frame
Dim swModelWindow As SldWorks.ModelWindow

Dim modelWindows() As Object
Dim sFrame(0 To 1) As String
Dim sActiveFileName() As String
Dim hWnd As Long
Dim Bool_Status As Boolean

Dim obj As Variant
Dim fileerror As Long
Dim filewarning As Long
Dim swDocSpecification As SldWorks.DocumentSpecification
Dim ChosenDoc As Variant
Private m_sngAnchorLeft As Single
Private m_sngAnchorTop As Single
Private m_blnSetAnchor As Boolean

'************
'Declare a bunch of Windows API functions:


Private Declare PtrSafe Function GetClassName Lib "user32" Alias _
"GetClassNameA" (ByVal hWnd As LongPtr, ByVal lpClass _
As String, ByVal nMaxCount As Long) As Long

Private Declare PtrSafe Function GetWindowRect Lib "user32" _
(ByVal hWnd As LongPtr, _
lpRect As RECT) As Long

Private Declare PtrSafe Function GetSystemMetrics32 Lib "user32" _
Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long


Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)

'End of Windows API functions
''''''''''''''''''''''''

Const DT_WID As Long = 78
Const DT_HT As Long = 79


Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type

Dim DeskWidth As Long
Dim DeskHt As Long
Dim swRect As RECT
Dim boolstatus As Boolean
Dim longstatus As Long, longwarnings As Long
Dim MainHandle As LongPtr
Dim ActiveHandle As LongPtr
Dim apiHandle As LongPtr
Dim ClassName As String

Const OVERSIZE As Long = -8

Const TOPWINDOWCLASS As String = "swMdiClient"


Public Static Property Let saveDir(ByVal strDataLet As String)
f_saveDir = strDataLet
Prp_Exit:
Exit Property
End Property

Public Property Get saveDir() As String
saveDir = f_saveDir
Prp_Exit:
Exit Property
End Property

Public Static Property Let SaveName(ByVal strDataLet As String)
f_SaveName = strDataLet
Prp_Exit:
Exit Property
End Property

Public Property Get SaveName() As String
SaveName = f_SaveName
Prp_Exit:
Exit Property
End Property

Public Property Get Frm_Status() As Boolean
Frm_Status = BoolFrm
lbl_Exit:
Exit Property
End Property


Private Function swApp_ActiveModelDocChangeNotify() As Long
'Stop
sActiveFileName(Me.MultiPage1.Value) = swApp.ActiveDoc.GetPathName
sActiveFileName(Me.MultiPage1.Value) = Mid(sActiveFileName(Me.MultiPage1.Value), InStrRev(sActiveFileName(Me.MultiPage1.Value), "\") + 1)
sActiveFileName(Me.MultiPage1.Value) = Left(sActiveFileName(Me.MultiPage1.Value), InStrRev(sActiveFileName(Me.MultiPage1.Value), ".") - 1)
'~~~~~~****~~~~~~
cmb_Active_File.Caption = sActiveFileName(Me.MultiPage1.Value)
lbl_Active_Model = sActiveFileName(Me.MultiPage1.Value)

End Function

Private Sub UserForm_Activate()
Window_size

Me.Top = (swRect.Top + OVERSIZE) * 0.75

End Sub

Private Sub UserForm_Deactivate()
m_blnSetAnchor = False
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 0 Then
sTemp = ""
Debug.Assert Not BoolDebug
If Not SaveName = "" Then
CopyTextToClipboard (SaveName)
sTemp = vbNewLine & "The file name is now copied to your clipboard!"
End If
MsgBox "You are chosing to manualy save the eDrawing" & sTemp, vbInformation
Debug.Print "Manually saving out eDrawing" & vbNewLine & SaveName
BoolFrm = False
Unload Me
End: End If
End Sub

Private Sub UserForm_Layout()
If m_blnSetAnchor Then
Me.Left = m_sngAnchorLeft
Me.Top = m_sngAnchorTop
End If
End Sub


Private Sub MultiPage1_Change()

Page_reset (Me.MultiPage1.Value)
'**************************************************************
Select Case Me.MultiPage1.Value

Case Is < 2

' If not BoolModal Then
' ' Modeless to Modal
' Me.Hide
' Me.Show vbModal
' boolModal = true
'
' End If

'change window position to center again
m_blnSetAnchor = False

'Stop
With Me
.Top = (swRect.Top + OVERSIZE) * 0.75
.Left = ((swRect.Right - swRect.Left + OVERSIZE) * 0.75) / 2 - .Width / 2
End With


If Me.MultiPage1.Value = 1 Then
Me.Txt_FolderPath.Value = saveDir

If Not BoolBrowse Then
Down_Translate Cmb_confirm2, 1
Size_Increase 1
BoolBrowse = True
End If: End If

Case 2

If BoolModal Then
' modal to non-modal
Me.Hide
Me.show vbModeless
BoolModal = False

End If

'change window position to upper right
With Me
.Top = (swRect.Top + OVERSIZE) * 0.75
.Left = (swRect.Right + OVERSIZE) * 0.75 - .Width
End With
Debug.Assert Not BoolDebug

If BoolDebug Then
'Determine Form postion
Debug.Print "Form.Left: " & Me.Left & " Form.Width: " & Me.Width
Debug.Print "Form.Top: " & Me.Top & " Form.Height: " & Me.Height
Stop: End If

If Not m_blnSetAnchor Then
m_sngAnchorLeft = Me.Left
m_sngAnchorTop = Me.Top
m_blnSetAnchor = True
End If

End Select: End Sub

Private Sub UserForm_Initialize()

Set swApp = Application.SldWorks
Set swFrame = swApp.Frame
Set swModel = swApp.ActiveDoc

BoolFrm = True

BoolModal = True


ReDim Frm_H(-1 To Me.MultiPage1.Pages.Count - 1)
ReDim Frm_W(-1 To Me.MultiPage1.Pages.Count - 1)

Dim I As Integer
For I = LBound(Frm_H) To UBound(Frm_H)
Frm_H(I) = Me.MultiPage1.Height
Frm_W(I) = Me.MultiPage1.Width
Next I

Incr_H = 24
Incr_W = 200
Max_Incr = 20

ReDim sActiveFileName(0 To Me.MultiPage1.Pages.Count - 1)
sActiveFileName(0) = swModel.GetPathName
sActiveFileName(0) = Mid(sActiveFileName(0), InStrRev(sActiveFileName(0), "\") + 1)
sActiveFileName(0) = Left(sActiveFileName(0), InStrRev(sActiveFileName(0), ".") - 1)

cmb_Active_File.Caption = sActiveFileName(0)
lbl_Active_Model = sActiveFileName(0)

'Start on Multipage 0
If Not Me.MultiPage1.Value = 0 Then
Me.MultiPage1.Value = 0
End If

'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' fill the FilesOpen() array

FilesOpen_read

If intFoundFiles < (UBound(FilesOpen) + 1) Then
ReDim Preserve optBtn(1, UBound(FilesOpen) + 1)
End If

For A = LBound(FilesOpen) To UBound(FilesOpen)
If A > 0 Then
Options_add FilesOpen(A).ModelDoc.GetTitle, (A), 1
collect_optBtn1.Add optBtn(Me.MultiPage1.Value, A), FilesOpen(A).ModelDoc.GetTitle

End If
Next A

A = A - 1
If A >= 1 Then
Size_Increase (A)
If A >= Max_Incr Then
Down_Translate Cmb_confirm1, Max_Incr
Else
Down_Translate Cmb_confirm1, (A)
End If
Else: Me.Cmb_confirm1.Enabled = False
End If

End Sub


Private Sub Window_size()

'First, get the entire desktop size.
DeskWidth = GetSystemMetrics32(DT_WID)
DeskHt = GetSystemMetrics32(DT_HT)

'Now get the rectangle for the SW child window area.
modelWindows = swFrame.modelWindows
Set swModelWindow = modelWindows(0)
' 'Get the model document in this model window
' Set swModel = swModelWindow.ModelDoc
' 'Show the model window
' swFrame.ShowModelWindow swModelWindow
' 'Get and print the model window handle
hWnd = swModelWindow.hWnd
Debug.Print (" Model window handle: " & hWnd)


'DocWindow = WindowUnderMouse
'It's the parent of the window under the mouse found below.
'GetWindowRect GetParent(DocWindow), swRect
GetWindowRect hWnd, swRect
Debug.Print "Desk:", DeskWidth, DeskHt
Debug.Print , "LEFT", "RIGHT", "TOP", "BOTT"
Debug.Print "SW Window:", swRect.Left, swRect.Right, swRect.Top, swRect.Bottom
Debug.Assert Not BoolDebug

End Sub


Private Sub cmb_Active_File_Click()

ChosenDoc = swModel.GetPathName
Confirm_Click True

End Sub

Private Sub Cmb_confirm1_Click()

Confirm_Click

End Sub

Private Sub Cmb_confirm2_Click()

If ChosenDoc <> "" Then
Confirm_Click True
Else
MsgBox "Proper file not selected."
End If

End Sub

Private Sub Cmb_comfirm3_Click()

ChosenDoc = swApp.ActiveDoc.GetPathName
Confirm_Click True

End Sub

Private Sub Confirm_Click(Optional Pre_select As Boolean = False)

Dim docType As Long


If Not Pre_select Then
ChosenDoc = Option_Selected

If IsEmpty(ChosenDoc) Then
Exit Sub
End If

End If

sFileType = Right(ChosenDoc, 7)
Select Case LCase(sFileType)
Case ".slddrw"
docType = 3
Case ".sldprt"
docType = 1
Case ".sldasm"
docType = 2
Case Else
MsgBox "Error: " & sFileType & vbNewLine & "File type not set up.", vbCritical
Exit Sub
End Select

If BoolDebug Then
Debug.Print "Current working directory is " & swApp.GetCurrentWorkingDirectory
End If

sFileName = Right(ChosenDoc, Len(ChosenDoc) - InStrRev(ChosenDoc, "\"))
swApp.SetCurrentWorkingDirectory (Left(ChosenDoc, Len(ChosenDoc) - Len(sFileName)))


sFrame(1) = "Please, be patient while macro is working."


If BoolModal Then
' modal to non-modal
Me.Hide
Me.show vbModeless
BoolModal = False
'Debug.Print "Modal State: " & ShowModal; Property
End If

swFrame.SetStatusBarText sFrame(1) ' feed status message to status bar

Set swModel = swApp.GetOpenDocumentByName(ChosenDoc)

Debug.Assert Not BoolDebug
If swModel Is Nothing Then
swApp.CreateNewWindow
swModel = swApp.ActivateDoc3(ChosenDoc, False, swRebuildOnActivation_e.swRebuildActiveDoc, fileerror)

Debug.Print " Error (0 = no errors) = " & fileerror


'If Not swModel.Visible Then

modelWindows = swFrame.modelWindows
For Each obj In modelWindows
'Get the model document in this model window
Set swModel = swModelWindow.ModelDoc
'Rebuild the document
swModel.EditRebuild3
Set swModel = Nothing
'Show the model window
Debug.Print ""
swFrame.ShowModelWindow swModelWindow
'Get and print the model window handle
hWnd = swModelWindow.hWnd
Debug.Print (" Model window handle: " & hWnd)
'Get and print the model title as it is seen in the model window's title bar
Debug.Print (" Model title as it seen in the model's window's title bar: " & swModelWindow.Title)

Next obj
Debug.Print swFrame.GetMenu

swFrame.IGetModelWindows (0)
'swModel.Visible = True
'End If
End If

Stop
'~~ *****~~ '

'Dim I As Integer
'For I = 0 To swFrame.GetModelWindowCount
'
'

'Stop
'Next I

'HWnd = swFrame.GetMenu
'Debug.Print "Model window count: " & swFrame.GetModelWindowCount
'& vbNewLine & "Submenus: "; swFrame.GetSubMenuCount(docType, HWnd) & _
'vbNewLine & "Open Documents: " & swApp.GetDocumentCount
Debug.Assert Not BoolDebug

swApp.ActivateDoc3 ChosenDoc, False, swRebuildOnActivation_e.swRebuildActiveDoc, fileerror

''Modeless to Modal
'Me.Hide
'Me.Show vbModal

File_Confirm (ChosenDoc)

End Sub

Private Sub Cmb_Browse_Click()

Dim Filter As String
Dim fileConfig As String
Dim fileDispName As String
Dim fileOptions As Long

'strFolder = BrowseFolder(Caption:="Select A Folder/Path", InitialFolder:=Txt_FolderPath.Value)

'note the use of the | character between filters
Filter = "All SOLIDWORKS Files (*.sldprt; *.sldasm; *.slddrw)|*.sldprt;*.sldasm;*.slddrw|SOLIDWORKS Model Files (*.sldprt; *.sldasm)|*.sldprt;*.sldasm|" & _
"SOLIDWORKS Drawing Files (*.slddrw)|*.slddrw|All Files (*.*)|*.*|"

strBrowseFile = swApp.GetOpenFileName("Select File", Txt_FolderPath.Value, Filter, fileOptions, fileConfig, fileDispName)

If Not strBrowseFile = "" Then
Debug.Print "File Name: " & strBrowseFile

strFolder = Left(strBrowseFile, InStrRev(strBrowseFile, "\"))
Debug.Print "Folder path: " & strFolder

Txt_FolderPath.Value = strFolder
ChosenDoc = strBrowseFile
End If: End Sub

Sub Page_reset(Optional I As Double = -1)

MultiPage1.Height = Frm_H(I)
MultiPage1.Width = Frm_W(I)
Me.Height = Frm_H(I) + 28.5
Me.Width = Frm_W(I) + 12

End Sub

Private Sub Options_add(Caption As String, n As Integer, Optional j As Double, Optional l As Double = 1, Optional m As Integer = 0)
Dim k As Integer: k = 0

'We can use Add method to add the new controls on run time
Set optBtn(Me.MultiPage1.Value, n) = Me.MultiPage1.SelectedItem.Controls.Add("Forms.OptionButton.1", "optButton" & Me.MultiPage1.Value & "-" & n, True)
n = n - m
If n >= (Max_Incr * l) Then
k = Int(n / (Max_Incr * l))
End If

With optBtn(Me.MultiPage1.Value, n + m)
.Caption = Caption
.Top = 18 + (n - Int(k * Max_Incr * l) + IIf(k > 0, 0, 0)) * Incr_H + j * Incr_H
.Left = 42 + Incr_W * k
.FONTNAME = "Calibri"
.FONTBOLD = False
.FONTSIZE = 9.75
.Height = 16
.Width = Incr_W - 14
.NAME = "OptionButton" & Me.MultiPage1.Value & "." & n
End With

End Sub

Private Sub Down_Translate(Item As Object, Optional X As Integer = 1)

Item.Top = Item.Top + Incr_H * X

End Sub

Private Sub Size_Increase(X As Integer, Optional Y As Double = 1)
Dim z As Integer
z = Me.MultiPage1.Value

If X < Max_Incr Then
MultiPage1.Height = Frm_H(z) + Incr_H * X
Me.Height = Frm_H(z) + 28.5 + Incr_H * X
ElseIf MultiPage1.Height < Frm_H(z) + Incr_H * Max_Incr Then
MultiPage1.Height = Frm_H(z) + Incr_H * Max_Incr
Me.Height = Frm_H(z) + 28.5 + Incr_H * Max_Incr
End If

If X >= Max_Incr * Y And MultiPage1.Width < (Frm_W(z) + Incr_W * Int(X / (Max_Incr * Y))) Then
MultiPage1.Width = Frm_W(z) + Incr_W * Int(X / (Max_Incr * Y))
Me.Width = Frm_W(z) + 12 + Incr_W * Int(X / (Max_Incr * Y))
End If

Frm_H(z) = Me.Height - 28.5
Frm_W(z) = Me.Width - 12


End Sub


Sub FilesOpen_read()

intFileOp = swFrame.GetModelWindowCount

Debug.Print "Number of open models in this SolidWork session: " & intFileOp

FilesOpen = swFrame.modelWindows

Debug.Assert Not BoolDebug
If BoolDebug Then 'BoolDebug = True
modelWindows = swFrame.modelWindows
For Each obj In modelWindows
Set swModelWindow = obj
' 'Get the model document in this model window
' Set swModel = swModelWindow.ModelDoc
' 'Show the model window
' swFrame.ShowModelWindow swModelWindow
'Get and print the model window handle
hWnd = swModelWindow.hWnd
Debug.Print (" Model window handle: " & hWnd)
'Get and print the model title as it is seen in the model window's title bar
Debug.Print (" Path and name of open document: " & swModel.GetPathName)
Debug.Print (" Model title as it seen in the model's window's title bar: " & swModelWindow.Title)
' 'Rebuild the document
' swModel.EditRebuild3
'
' Set swModel = Nothing

Next obj


Dim index As Integer
For index = LBound(FilesOpen) To UBound(FilesOpen)

Set swModel = FilesOpen(index).ModelDoc
Debug.Print "Path and name of open document: " & swModel.GetPathName
Debug.Print "Get Title call: " & swModel.GetTitle
Next index

End If

End Sub

Function Option_Selected()
Dim X As Integer

For X = LBound(optBtn, 2) To UBound(optBtn, 2)

If Not (optBtn(MultiPage1.Value, X) Is Nothing) Then

If optBtn(MultiPage1.Value, X) = True Then
Select Case MultiPage1.Value
Case 0
If X <= A Then
Option_Selected = FilesOpen(X).ModelDoc.GetPathName
'Else
End If
Case 1
Option_Selected = strFolder & FolderFiles(X)
End Select
Exit Function: End If: End If
Next X

End Function

Private Sub File_Confirm(swDoc)
Dim sSaveType As String


Select Case LCase(sFileType)
Case ".slddrw"
sSaveType = ".EDRW"
Case ".sldprt"
sSaveType = ".EPRT"
Case ".sldasm"
sSaveType = ".EASM"
Case Else
Debug.Print "Error: " & sFileType & vbNewLine & "File type incorrect."
Unload Me
End Select


If MsgBox("You have selected " & sFileName & vbNewLine & "This will be saved as a: " & sSaveType & " file." _
& vbNewLine & "Are you ok with this Selection?", vbYesNo + vbQuestion) = vbNo Then
Unload Me
Frm_eDraw_file_choose.show
End If
BoolFrm = False
Unload Me
End Sub

Form3:Frm_FoldersOpen

Private Sub CmbConfirm_Click()
Dim tempstr As String
If saveDir = "" Then End

tempstr = Left(saveDir, InStr(saveDir, "\03-Design") - 1)

If ChBx_Publish Then
ShowFolder (tempstr & Settings(1, 0))
End If

If ChBx_CNC Then
ShowFolder (tempstr & Settings(1, 1))
End If

End Sub


Private Sub UserForm_Initialize()

Call SystemButtonSettings(Me, False)

End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then

Cancel = True
MsgBox "Please Select folders to open & Confirm"

End If
End Sub

The "Publish-Settings.txt" is formatted as this:

Array: 2;2
}
' Project Folder Tree
UNC: \Drafting\Model\; 03-Design\Drafting\
}
' Published File Locations
Publish 03-Design: 00-Published\DraftingDrawing\; 00-Published\Production\CNCFiles\
}

RJ
RJ 2021-04-08

Hi,

OpenDoc6 should open the referenced model. The issue you are facing might be because the drawing file and the referenced model have the same name. It is always advised to use the complete file path name (Path Name + File Name + Extension) in OpenDoc6 file name parameter so that all discrepancies are automatically (and logically) cleared by SW.

Hope it helps!!!

Rajat Jain

AT
AT 2021-04-08

I presume your reference is invisible. Try to set the IModelDoc2::Visible property of this document to True before calling the ActivateDoc API.

DG
DG 2021-04-08

Arthur McRae wrote:

I have tried using IActivateDoc3 as well but keep getting errors as well.

Below are the codes I had been using with no errors. So what error you are getting? Share your completed macro to debug.

Option Explicit

Dim swApp As SldWorks.SldWorks

Dim swModel As SldWorks.ModelDoc2

Dim errors As Long

Sub main()

    Set swApp = Application.SldWorks   

    swApp.ActivateDoc3 "Get the model referenced by the drawing here and put the full path/name here", False, swRebuildOnActivation_e.swRebuildActiveDoc, errors  

End Sub

AM
AM 2021-04-08

I have tried using IActivateDoc3 as well but keep getting errors as well.