How can I load FileDialog? (VBA)

Hello all,

how can I load FileDialog from UserForm? I need load folder path to TextBox and I need open FileDialog via button.  How can I set it? If I use this code:

<p>    Dim fDialog As FileDialog, result As Integer</p><p>    Set fDialog = Application.FileDialog(msoFileDialogFolderPicker)</p><p></p><p>    'Optional: FileDialog properties</p><p>    fDialog.Title = "Select a folder"</p><p>    fDialog.InitialFileName = "C:\\"</p><p>     </p><p>    If fDialog.Show = -1 Then</p><p>      Debug.Print fDialog.SelectedItems(1)</p><p>    End If</p>

macro end with error: Object doesn't support this property or method.

Do I have to set some object as SldWorks? In my opinion this is process in Windows, not in Solidworks. I haven't got allow some library (Tools -> References).

Thnaks a lot for your answers.

SolidworksApi macros
Answers 31
CC
CC 2017-10-12 Best Answer

Please read this​

FV
FV 2017-10-12

Thnaks, this is for VB.NET. I nedd this for VBA. I'm sorry, A was lost :-)

CC
CC 2017-10-12

Then you need some Window API call to get a file dialog box

Add a module and copy/paste this code

<p>Option Explicit</p><p></p><p></p><p>Public Type BROWSEINFO</p><p>    hOwner As LongPtr</p><p>    pidlRoot As LongPtr</p><p>    pszDisplayName As String</p><p>    lpszTitle As String</p><p>    ulFlags As LongPtr</p><p>    lpfn As LongPtr</p><p>    lParam As LongPtr</p><p>    iImage As LongPtr</p><p>End Type</p><p></p><p></p><p>Public Const BIF_RETURNONLYFSDIRS = &H1</p><p>Public Const BIF_DONTGOBELOWDOMAIN = &H2</p><p>Public Const BIF_STATUSTEXT = &H4</p><p>Public Const BIF_RETURNFSANCESTORS = &H8</p><p>Public Const BIF_BROWSEFORCOMPUTER = &H1000</p><p>Public Const BIF_BROWSEFORPRINTER = &H2000</p><p>Public Const BIF_NEWDIALOGSTYLE = &H40</p><p>Declare PtrSafe Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As LongPtr, ByVal pszPath As String) As LongPtr</p><p>Declare PtrSafe Function SHBrowseForFolder Lib "shell32.dll" Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As LongPtr</p><p>Public Function GetFolder(ByVal sTitle As String) As String</p><p></p><p></p><p>    Dim bInf As BROWSEINFO</p><p>    Dim retval As LongPtr</p><p>    Dim PathID As LongPtr</p><p>    Dim RetPath As String</p><p>    Dim Offset As Integer</p><p>    </p><p>    bInf.lpszTitle = sTitle</p><p>    bInf.ulFlags = BIF_NEWDIALOGSTYLE</p><p>    PathID = SHBrowseForFolder(bInf)</p><p>    RetPath = Space$(512)</p><p>    </p><p>    retval = SHGetPathFromIDList(ByVal PathID, ByVal RetPath)</p><p>    </p><p>    If retval Then</p><p>        </p><p>        Offset = InStr(RetPath, Chr$(0))</p><p>        GetFolder = Left$(RetPath, Offset - 1)</p><p>    </p><p>    End If</p><p></p><p></p><p>End Function</p>
AJ
AJ 2017-10-12

Use DotNetTools for VBA – CADHERO consulting SUARL​ . Save yourself the hassle of Windows API calls.

It has the .Net BrowseToFileDialog class exposed.

Cheers,
Amen

CADHERO consulting SUARL – SOLIDWORKS API/PDM Design Automation & Training – SOLIDWORKS VBA MACROS, SOLIDWORKS Addins an…

FV
FV 2017-10-12

Wow, I've waited some easier solution.

But... How do I call this function? Call ModuleName.GetFolder? It's not function...

CC
CC 2017-10-12

Just call:

GetFolder("Select a folder or create a new one:")

or use tool created by Amen

CC
CC 2017-10-12

It's totally cool - Thx for sharing !!!

JC
JC 2017-10-12

yeah. do this.

abuse ​ s code he created.

FV
FV 2017-10-12

OK, thanks a lot.

CC
CC 2017-10-12

no problem

FV
FV 2017-10-17

Hello,

siplier code maybe:

<p>Sub FolderSelection()</p><p>    Dim MyPath As String</p><p>    MyPath = SelectFolder("Select Folder", "")</p><p>    If Len(MyPath) Then</p><p>        MsgBox MyPath</p><p>    Else</p><p>        MsgBox "Cancel was pressed"</p><p>    End If</p><p>End Sub</p><p></p><p>'Both arguements are optional. The first is the dialog caption and</p><p>'the second is is to specify the top-most visible folder in the</p><p>'hierarchy. The default is "My Computer."</p><p></p><p>Function SelectFolder(Optional Title As String, Optional TopFolder _</p><p>                         As String) As String</p><p>    Dim objShell As New Shell32.Shell</p><p>    Dim objFolder As Shell32.Folder</p><p></p><p>'If you use 16384 instead of 1 on the next line,</p><p>'files are also displayed</p><p>    Set objFolder = objShell.BrowseForFolder _</p><p>                            (0, Title, 1, TopFolder)</p><p>    If Not objFolder Is Nothing Then</p><p>        SelectFolder = objFolder.Items.Item.Path</p><p>    End If</p><p>End Function</p>
JG
JG 2018-03-08

Can it be modified to see network drives also?

AJ
AJ 2018-03-17

My answer does network drives.

JG
JG 2018-03-19

Indeed. I needed to map network drive

NR
NR 2019-03-27

This is working in Excel -

I can't get it working in SW - Does somebody know how to solve this?

//Niels

'https://software-solutions-online.com/excel-vba-application-filedialog-object/

Sub GetFile()

Dim SelectedItem As String

With Application.FileDialog(msoFileDialogFilePicker)

If .Show = -1 Then

'if user clicks OK

SelectedItem = .SelectedItems(1)

MsgBox "You have selected: " & SelectedItem

Else

'if user clicks Cancel

End If

End With

End Sub

comment imagecomment image
NR
NR 2019-03-27

'Found this from Deepak

'https://forum.solidworks.com/thread/219602

Option Explicit

Dim swapp As SldWorks.SldWorks

Dim Filter As String

Dim fileName As String

Dim fileConfig As String

Dim fileDispName As String

Dim fileOptions As Long

Sub main()

Set swapp = Application.SldWorks

Filter = "SOLIDWORKS Drawing Files (*.slddrw)|*.slddrw|Excel(*.xls)|*.xls|"

fileName = swapp.GetOpenFileName("Select File", "", Filter, fileOptions, fileConfig, fileDispName)

MsgBox fileName

End Sub

JB
JB 2019-03-27
<p>Niels Raahauge wrote:</p><p></p><p>This is working in Excel - </p><p>I can't get it working in SW - Does somebody know how to solve this?</p><p>//Niels</p><p style="min-height: 8pt; padding: 0px;"></p><p></p><p><span>'</span><a class="jive-link-external-small" href="/external-link.jspa?url=https%3A%2F%2Fsoftware-solutions-online.com%2Fexcel-vba-application-filedialog-object%2F" rel="nofollow" target="_blank" data-community-id="1">https://software-solutions-online.com/excel-vba-application-filedialog-object/</a></p><p style="min-height: 8pt; padding: 0px;"></p><p>Sub GetFile()</p><p>Dim SelectedItem As String</p><p>With Application.FileDialog(msoFileDialogFilePicker)</p><p>If .Show = -1 Then</p><p>'if user clicks OK</p><p>SelectedItem = .SelectedItems(1)</p><p>MsgBox "You have selected: " & SelectedItem</p><p>Else</p><p>'if user clicks Cancel</p><p>End If</p><p>End With</p><p>End Sub</p>

So... When you are running VBA from Excel, "Application" is Excel. Excel has a .FileDialog function.

When you're running VBA from SolidWorks, "Application" is SolidWorks, which doesn't have a .FileDialog function.

You can create an instance of Excel and use that application sort of in stealth mode. There's an example of doing that here:

How can you use a text editor to determin SolidWorks File Version - DASSAULT: SOLIDWORKS 3D Design - Eng-Tips

comment imagecomment image
NR
NR 2019-03-27

Hi Josh

Thank you for the answer.

I got an error when doing that..

Sub GetFile()

Dim swApp As SldWorks.SldWorks
Dim myxlApp As Excel.Application

Dim PickedFiles As Variant

Dim SelectedItem As String

Set myxlApp = CreateObject("Excel.Application")

With Application.FileDialog(msoFileDialogFilePicker)
If .Show = -1 Then
'if user clicks OK
SelectedItem = .SelectedItems(1)
PickedFiles = SelectedItem
Else
'if user clicks Cancel
End If
End With
Set myxlApp = Nothing

MsgBox PickedFiles
End Sub

comment imagecomment image
DG
DG 2019-03-28

Is GetOpenFileName method not working for SW files?

JB
JB 2019-03-28

You are STILL running the code from inside SolidWorks. Therefore, "Application" is SolidWorks. Application.FileDialog will not work unless you are RUNNING THE CODE IN EXCEL.

myxlApp.FileDialog should work in your code above.

NR
NR 2019-03-29

Hi Deepak

It does, thank you for sharing code

I found the excel object smart - there is a lot of functions.

But it seams not possible to use in SW.

'https://software-solutions-online.com/excel-vba-application-filedialog-object/

BR Niels

DH
DH 2019-06-25

‌ is there a way to set a default path for your folder dialog box to open to? (Nice bit of work by the way). It would save me numerous repeated clicks if I could start out in a specific folder within my My Documents area.

Thanks,

Daen

CC
CC 2019-06-25

Daen Hendrickson wrote:

Christian Chu is there a way to set a default path for your folder dialog box to open to? (Nice bit of work by the way). It would save me numerous repeated clicks if I could start out in a specific folder within my My Documents area.

 

Thanks,

Daen

You mean using the path you select the last time as a default? if yes, then you can use SaveSetting and GetSetting

Something like this:

The first time running the macro, you'd get "C\Temp" as your default

but after selecting a new path, it'll be saved in the registry in "NewPathName" for your use next time

in the form, add textbox1 and commandbutton1 and add these lines:

Private Sub UserForm_Activate()
Dim getPathString As String
getPathString = GetSetting("MyMacro", "MacroName", "PathNameStr", "C:\Temp")
TextBox1.Text = getPathString
End Sub
Private Sub CommandButton1_Click()
TextBox1.Text = GetFolder("Select a destination folder or create a new one:")
SaveSetting "MyMacro", "MacroName", "PathNameStr", TextBox1.Text
End Sub

DH
DH 2019-06-25

Thanks ‌. I'll work with this.

I would like to be able to set the default for the first time the dialog opens.

Daen

DH
DH 2019-06-26

‌,

After reviewing your suggestion I see two issues:

  1. I do not have registry write permission on my machine
  2. My "rusty" coding ability understands your snippet updates Textbox1.text with values pulled from the registry (and later saves back to the registry). I already have a similar behavior with an ini file. What I don't see in your code is where to control the default folder path that your dialog box opens with.

When I click my CommandButton1 I want to launch your dialog box and have that dialog box open to the folder already specified in Textbox1.

Thanks for your patience.

Daen

CC
CC 2019-06-26

Daen,

if you don't have permission to write to registry then it's fine. Use ini file instead to save the last selected default folder 

As Josh and others mentioned, File dialog is not included in the SW API; however, you can run it on Excel App

Here is the code you can try

all you need to change in the code is to retrieve  the Selected Default Folder from your .ini file and save in saveDefaultFolderStr

Private Sub CommandButton1_Click()
' TextBox1.Text = GetFolder("Select a destination folder or create a new one:")
' SaveSetting "MyMacro", "MacroName", "PathNameStr", TextBox1.Text

Dim saveDefaultFolderStr As String
saveDefaultFolderStr = "C:\Temp"
newBrowseForFolder (saveDefaultFolderStr)
End Sub
Function newBrowseForFolder(saveDefaultFolderStr As String) As String
Dim xlApp As Excel.Application
Set xlApp = CreateObject("Excel.Application")

Dim selectedFolderString As String
With xlApp.FileDialog(msoFileDialogFolderPicker)
.Title = "Select folder"
.ButtonName = "Select"
.InitialFileName = saveDefaultFolderStr
If .Show = -1 Then
selectedFolderString = .SelectedItems(1)
MsgBox Chr(34) & selectedFolderString & Chr(34) & " is now your default selected folder - Please save it to the ini file"
Else
MsgBox Chr(34) & saveDefaultFolderStr & Chr(34) & " is still Default Folder"
End If
End With
Set xlApp = Nothing
End Function

DH
DH 2019-06-26

,

Worked perfectly! Thanks for the helping hand.

Daen

CC
CC 2019-06-26

Daen Hendrickson wrote:

Christian Chu,

 

Worked perfectly! Thanks for the helping hand.

 

Daen

Glad it works out for you

Just a little note: If you only need to read 1 line of folder string of characters from a text file, why don't you use simple text file instead of ini 

see this thread of how to use it 

https://forum.solidworks.com/thread/202095

DH
DH 2019-06-27

‌,

I had the ini file already in place to handle other things so reading in a key for the default start folder was minimal additional effort.

thanks,

Daen

CC
CC 2019-06-27

Daen Hendrickson wrote:

Christian Chu,

 

I had the ini file already in place to handle other things so reading in a key for the default start folder was minimal additional effort.

 

thanks,

Daen

Ok, cool!