I know how to let the user click on a button to navigate to a specific file to open.
Code:
Private Sub CommandButton2_Click()
Dim vaFiles As Variant
vaFiles = Application.GetOpenFilename()
ActiveSheet.Range("B9") = vaFiles
End Sub
I want a second button that will let the user navigate to a folder to save the .pdf
file that my program creates.
The problem: The GetOpenFilename
requires the user to click on a file. If there's no file in the folder then there's nothing the user can do.
Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).
To get current file's full path, you can use the os. path. abspath function. If you want only the directory path, you can call os.
Extension or Filename Extension or File Extension: I like the last one.
Techopedia Explains Absolute PathAn absolute path always contains the root elements and the complete list of directories to locate the specific file or folder. All the information required to locate the file or folder is available in the absolute path.
Use the Application.FileDialog
object
Sub SelectFolder()
Dim diaFolder As FileDialog
Dim selected As Boolean
' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
selected = diaFolder.Show
If selected Then
MsgBox diaFolder.SelectedItems(1)
End If
Set diaFolder = Nothing
End Sub
In the VBA Editor's Tools menu, click References... scroll down to "Microsoft Shell Controls And Automation" and choose it.
Sub FolderSelection()
Dim MyPath As String
MyPath = SelectFolder("Select Folder", "")
If Len(MyPath) Then
MsgBox MyPath
Else
MsgBox "Cancel was pressed"
End If
End Sub
'Both arguements are optional. The first is the dialog caption and
'the second is is to specify the top-most visible folder in the
'hierarchy. The default is "My Computer."
Function SelectFolder(Optional Title As String, Optional TopFolder _
As String) As String
Dim objShell As New Shell32.Shell
Dim objFolder As Shell32.Folder
'If you use 16384 instead of 1 on the next line,
'files are also displayed
Set objFolder = objShell.BrowseForFolder _
(0, Title, 1, TopFolder)
If Not objFolder Is Nothing Then
SelectFolder = objFolder.Items.Item.Path
End If
End Function
Source Link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With