I'm trying to write a bit of code that allows the user to choose the file path of a folder before exporting data in a separate .xlsx file to that folder. Its easy enough to look up a folder's path beforehand and hard code it in, but I want this program to allow the user to choose a folder each time. As it is, I have this function that utilizes the excel open file dialog box. From there, I am able to find the folder I need, and just copy the file path from the top bar and hit cancel. Here's the code:
Function GetFileDestination() As String
Dim DataObj As New MSForms.DataObject
'This MsgBox just tells the user what to do
MsgBox "To get the file Destination, the 'Open File' Dialog Box will open. Go to the folder_
you want to use, click on the bar at the top, and copy the destination. Then hit Cancel",_
vbOKOnly, "Finding the File Destination"
Application.Dialogs(xlDialogOpen).Show
DataObj.GetFromClipboard
GetFileDestination = DataObj.GetText
End Function
This does the job, but it seems pretty sloppy, since it forces the user to manually copy the file path needed and then cancel the open file dialog box.
Does anyone know a more creative and clean way about this while still keeping the same functionality?
Thanks in advance!
Function GetFolder(strPath As String) As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Here's the description:
Application.FileDialog(msoFileDialogFolderPicker) - The folder dialog prompts the user to
select a directory path.
strPath - Default path which will be passed on to the function.
show - If the user chooses to cancel the dialog, the value '0' will be assigned, otherwise the value '-1' is assigned.
GetFolder = sItem - The path of the folder selected/opened is returned by this statement,
else Null is returned if Cancel button is clicked.
Hope this clears the overall logic used.
Related
I have a requirement where I need to select a folder instead of a file, while clicking a browse button.
The code to select a file, while clicking the browse button will be as below.
Case "Browse"
DlgText "path", GetFilePath(,"*.*","C:\","Open sheet")
How to change this to select a folder, instead of a file.
Thanks in advance
Please, try the next way:
Case "Browse"
Dim folderPath As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select the necessary folder!"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select any folder..."
Exit Sub
End If
folderPath = .SelectedItems(1)
End With
'your existing code...
Edited:
If you work in Windows OS, even if ERStudio, which I am not fammiliar to, does not expose such a method, please try the next way, using VBScript objects:
Case "Browse"
Dim objSh As Object, objFold As Object, strStartFolder As String, strFolder As String
strStartFolder = "C:\" 'you can use here what starting folder you want
Set objSh = CreateObject("Shell.Application")
Set objFold = objSh.BrowseForFolder(0, "Select The necessary Folder", 0, strStartFolder)
If IsObject(objFold) Then strFolder = objFold.Self.Path
MsgBox strFolder 'use it where necessary and comment this testing line...
'your existing code...
My code is simple.
I have copied it off of the VBA example site: https://learn.microsoft.com/en-us/office/vba/api/office.filedialog
Additionally, every other variation I can find online has the same problem.
All I am attempting is to open a File Dialogbox (Similar to a file explorer) where a user can select a folder or files.
However, I carry on getting this error:
It then highlights this line of code:
Additionally, I have added references to Microsoft Office 16.0 Object Library, and everything I can think of:
How do I fix this or get this to Run?
Thank You
Here is the Code:
Sub Main()
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Declare a variable to contain the path
'of each selected item. Even though the path is aString,
'the variable must be a Variant because For Each...Next
'routines only work with Variants and Objects.
Dim vrtSelectedItem As Variant
'Use a With...End With block to reference the FileDialog object.
With fd
'Use the Show method to display the File Picker dialog box and return the user's action.
'The user pressed the button.
If .Show = -1 Then
'Step through each string in the FileDialogSelectedItems collection.
For Each vrtSelectedItem In .SelectedItems
'vrtSelectedItem is aString that contains the path of each selected item.
'You can use any file I/O functions that you want to work with this path.
'This example displays the path in a message box.
MsgBox "The path is: " & vrtSelectedItem
Next vrtSelectedItem
'The user pressed Cancel.
Else
End If
End With
'Set the object variable to Nothing.
Set fd = Nothing
End Sub
Disclaimer: I'm sure there is a better/more correct way to do this but it works for me in VBA for SolidWorks. I am not a real programmer. Just trying to help because I know how few resources there are on VBA programming in SW.
All I really did was add the Excel Object library and change Application to Excel.Application.
Despite what GSerg said, there can be an Excel.Application if you add the Excel object library as a reference.
Despite macropods condescension, you are not stuck with what SW provides or the generic file browser and you don't need to re-install Office or SW. The generic file browser doesn't show your Quick Access items. SolidWorks doesn't run on Mac OS. His "answer" does not work in SW VBA.
Here is my working function (started with code from here):
Function GetFolder(Title As String)
Dim folder As FileDialog
Dim selected_folder As String
Set folder = Excel.Application.FileDialog(msoFileDialogFolderPicker)
With folder
.AllowMultiSelect = False
.ButtonName = "Ok"
.Filters.Clear
.InitialFileName = Excel.Application.DefaultFilePath
.Title = Title
If .Show <> -1 Then GoTo NextCode
selected_folder = .SelectedItems(1)
End With
NextCode:
Debug.Print selected_folder
GetFolder = selected_folder
Set folder = Nothing
End Function
I added the Excel & Office Object Libraries to the default VBA SW:
If you have a way to do this that shows the Quick Access items without having to use the Excel Object Library I'm very interested!
I assume you're using a Windows system, since Application.FileDialog is not available/fully supported on Macs.
I suggest you start over, without adding a plethora of irrelevant references. The following works just fine without adding any to the default references:
Sub Demo()
Dim fd As FileDialog, vrtSelectedItem As Variant
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
MsgBox "The path is: " & vrtSelectedItem
Next
End If
End With
Set fd = Nothing
End Sub
If the code still doesn't work for you, a repair/reinstall of Office or your SolidWorks installation is most likely called for.
For code that works on Macs and PCs, see: https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-msoffice_custom-mso_365hp/showing-dialogs-word-for-mac-vba/513ea974-378d-4ebe-95c3-a0221a9287ff
I'm using this code snippet to allow a user to browse for a folder where to save a file. The problem occurs when the user doesn't browse to other folders (so he wants to save into the default folder).
So when a user runs this code and immediately clicks OK, I get this error:
Test KIT exchange
Path does not exist
Function GetFolder(Optional strPath As String) As String
Dim fldr As Object
Dim sItem As String
Set fldr = Application.FileDialog(4)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
If strPath <> "" Then
.InitialFileName = strPath
End If
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
If the user browses to the parent folder and then back to the default folder, it runs as expected.
What could be the cause here?
If strPath = "D:\Folder" shows the correct folder, but fails when you click OK.
If strPath = "D:\Folder\" runs fine.
Though the output is again D:\Folder, which is kinda odd if you ask me...
Since the FileDialog object may be used for either a folder or file selection depending on the DialogType argument supplied, if you omit the trailing path delimiter from the InitialFilename property, the supplied value will be interpreted as a filename with the edit box populated with the name of the 'file'.
I have a bit of code which I am trying to improve but having some issues.
The code is currently:
Sub TestListFilesInFolder()
'Workbooks.Add ' create a new workbook for the file list
' add headers
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker) ' Tried using a FileDialog Application but had no luck
With Range("A1")
.Formula = "Folder contents:"
.Font.Bold = True
.Font.Size = 12
End With
Range("A3").Formula = "Old File Path:"
Range("B3").Formula = "File Type:"
Range("C3").Formula = "File Name:"
Range("D3").Formula = "New File Path:"
Range("A3:H3").Font.Bold = True
ListFilesInFolder "L:\Pictures\A B C\B526 GROUP", True
' ListFilesInFolder fd, True ' I tried replacing the above line with this line but get an error
' list all files included subfolders
End Sub
Line 5 and 6 is a part I have added in where I am trying to get a file dialog to open where the user can choose the folder for the code to work on.
Also The commented out line near the bottom starting ListFilesInFolder is the one I tried inserting to replace the line above it.
The start of the next bit of code is:
Sub ListFilesInFolder(SourceFolderName As String, IncludeSubfolders As Boolean)
So it uses the folder and subfolders of that folder defined in the first sub.
Any help on this would be appreciated.
Regards,
Sam
You're passing fd as the first parameter to your ListFilesInFolder sub. This sub accepts a String as the first parameter, not a FileDialog.
Here's some sample code that, when executed, will open a file dialog and let the user select a folder. Once selected, it will print the path of the folder to B2. If no folder is selected (e.g. dialog is closed or canceled), B2 will contain the text No item selected.
I think you should create a new workbook and play around with this macro. Set a break point and walk through it, see what it's actually doing. Then you can alter it to make it work for your specific needs.
Public Sub SelectExportDestinationPath()
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then
sItem = "No item selected"
Else
sItem = .SelectedItems(1)
End If
End With
'if trailing slash is not found, add it
If Len(sItem) > 0 And InStr(Len(sItem), sItem, Application.PathSeparator, vbCompareText) = 0 Then
sItem = sItem & Application.PathSeparator
End If
Sheet1.Cells(2, 2).Value = sItem
Set fldr = Nothing
End Sub
make sure you have the appropriate reference picked:
Press Alt+F11 to open the VB Editor. In that window, choose menu items Tools -> References..., then look down the list for Microsoft Office XXX Object Library
It's 11.0 for Access 2003, 10.0 for Access 2002; 9.0 for Access 2000, 8.0 for Access 97 -- pick the right one.
Put a check mark in the box next to that reference, then close the dialog.
or, use the actual values, not the mso values
msoFileDialogOpen=1
msoFileDialogSaveAs=2
msoFileDialogFilePicker=3
msoFileDialogFolderPicker=4
Please help me make my OpenFileDialog showing my PowerPoint project directory.
i tried .InitialDirectory = "C:\\" ,but it doesn't work. Can i adapt this to vba? Thanks.
This is nearly copied from the Powerpoint VBA help. It uses FileDialog instead of OpenFileDialog(which I had difficulty finding in relation to PowerPoint). It sets the InitialFileName to C:\ so that it will prompt in that location. Just place this in a module, it should be easy to modify to your specific needs:
Sub fileDialogExample()
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
'Declare a variable for the directory path.
Dim directory As String
'Set the directory path
directory = "C:\"
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Declare a variable to contain the path
'of each selected item. Even though the path is aString,
'the variable must be a Variant because For Each...Next
'routines only work with Variants and Objects.
Dim vrtSelectedItem As Variant
'Use a With...End With block to reference the FileDialog object.
With fd
'Change the initial directory\filename
.InitialFileName = directory
'Use the Show method to display the File Picker dialog box and return the user's action.
'The user pressed the button.
If .Show = -1 Then
'Step through each string in the FileDialogSelectedItems collection.
For Each vrtSelectedItem In .SelectedItems
'vrtSelectedItem is aString that contains the path of each selected item.
'You can use any file I/O functions that you want to work with this path.
'This example displays the path in a message box.
MsgBox "The path is: " & vrtSelectedItem
Next vrtSelectedItem
'The user pressed Cancel.
Else
End If
End With
'Set the object variable to Nothing.
Set fd = Nothing
End Sub