Select filename using FileDialog - vba

I am trying to get a fullpath and filename using the file dialog from MS Access VBA.
What I am trying to do is to open the file Dialog on button click by calling this function. This function should return the fullpath and filename that was selected from the filedialog.
I commented the loop part because I only want to select single file.
This function is returning an error Error: 0 after I select a file
So far this is my code.
Anyone can figure out what's wrong?
Thanks
Public Function SelectTheFile() As String
On Error GoTo SelectTheFile_ErrorHandler
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Title = "Please select one file"
If .Show = True Then
'For Each varFile In .SelectedItems
'SelectTheFile = varFile
'Debug.Print SelectTheFile
'Next
SelectTheFile = .SelectedItems(1)
Debug.Print SelectTheFile
Else
Debug.Print "Cancel"
End If
End With
SelectTheFile_ErrorHandler:
Set fd = Nothing
MsgBox "Error " & Err & ": " & Error(Err)
End Function

your code always reach the SelectTheFile_ErrorHandler: section whatever the file dialog result
you must exit the function before that section
Public Function SelectTheFile() As String
On Error GoTo SelectTheFile_ErrorHandler
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Title = "Please select one file"
If .Show = True Then
'For Each varFile In .SelectedItems
'SelectTheFile = varFile
'Debug.Print SelectTheFile
'Next
SelectTheFile = .SelectedItems(1)
Debug.Print SelectTheFile
Else
Debug.Print "Cancel"
End If
End With
Exit Function '<==== exit here, otherwise code goes on to following section
SelectTheFile_ErrorHandler:
Set fDialog = Nothing
MsgBox "Error " & Err & ": " & Error(Err)
End Function

Try just using this:
Application.GetOpenFilename
That works for me and saves the full file path without actually opening the file. Much simpler unless I am missing what you're trying to do. Read more here in the docs: https://msdn.microsoft.com/en-us/library/office/ff834966.aspx

Related

I am getting an unknown file path error and I can't figure out why?

I have a VBA code section in Access that runs a query using inputs on a form (one input is for the query, the other is for the filename to be saved). For some reason I am getting an invalid file path error but the path is legit as I can tell. Why I am I getting the error? FileName is the desired name of the spreadsheet to be saved from the form.
This is what I get from access for the error:
Private Sub AllPaybacks_Click()
Dim getFolder As Object
Dim sLoc As String
Dim fileN As String
Set getFolder = Application.FileDialog(msoFileDialogFolderPicker)
With getFolder
.AllowMultiSelect = False
getFolder.InitialFileName = FileName.Value
fileN = getFolder.InitialFileName
If .Show = True Then
sLoc = getFolder.SelectedItems(1) & "\"
End If
End With
DoCmd.OpenQuery "PaybackQ"
DoCmd.TransferSpreadsheet acExport, , "PaybackQ", sLoc & fileN & ".xlsx", True
End Sub
I was using the wrong syntax to solve this. In order to use the data in my text box on my form as the file name I needed to do the following.
Private Sub AllPaybacks_Click()
Dim getFolder As Object
Dim sLoc As String
Dim fileN As String
Set getFolder = Application.FileDialog(msoFileDialogFolderPicker)
With getFolder
.AllowMultiSelect = False
fileN = Forms!PaybackSearchF!FileName
If .Show = True Then
sLoc = getFolder.SelectedItems(1) & "\"
End If
End With
DoCmd.OpenQuery "PaybackQ"
DoCmd.TransferSpreadsheet acExport, , "PaybackQ", sLoc & fileN & ".xlsx", True
End Sub
fileN = Forms!PaybackSearchF!FileName appropriately read in the string in the text box from my form.

VBA Using FileDialog as Folder Path in a Loop

I am trying to make a copy of a workbook that I have, based on list of IDs. I have got this to work OK if I hard code the path, however I can't figure out how to do this where specifying the path using msoFileDialogFolderPicker.
I have tried a number of variations depending on what I have found online and have got as far as below but stuck. Help appreciated.
Dim xFilepath As Variant
Dim xFilename As String
xFilepath = Application.FileDialog(msoFileDialogFolderPicker)
xFilename = Range("Table9[ProgramID]") & " Product Financial Allocation" & ".xlsb"
With xFilepath
.Title = "Choose Destination"
.SHOW
mypath = .SelectedItems(1) & "\"
End With
mypath = mypath
Sheets("FILES").Range("A3").Select
For i = 1 To 3
Sheets("FILES").Range("A" & i).copy Sheets("TEMPLATE").Range("Table9[ProgramID]")
ActiveWorkbook.SaveCopyAs Filename:=mypath & Filename
FileFormat = 50
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
Workbooks.Open Filename:=mypath & Filename
Call DeleteQueries
ActiveWorkbook.Save
ActiveWorkbook.Close
Next i
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub
You can use the following code can be used to select folder and then you can append the folder path with file name.
Sub ChooseFolder()
Dim sFolder As String
' Open the select folder prompt
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a Folder"
If .Show = -1 Then ' if OK is pressed
sFolder = .SelectedItems(1)
End If
End With
Filename = "Test.xlsx"
Filepath = sFolder + "\" + Filename
If sFolder <> "" Then ' if a file was chosen
MsgBox Filepath 'Use this for further processing
End If
End Sub
Following code can be used select single file.
Private Sub ChooseFile()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel File", "*.xlsx"
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
MsgBox txtFileName
End Sub

Saving a File in Desired Folder Through Browsing With VBA

Writing a code to save a file with a defined filename to a specific folder entered by the user. However the file is being saved in a location previous to the specified location. For example I provide file save path as "C:\Users\arorapr\Documents\PAT" but the file is saving it in the path "C:\Users\arorapr\Documents". I have written the below code.
File_Name = Format(Now(), "DDMMYYYY") & "_" & LName & EmpIN & "_" & Range("C6").Value & "_" & Range("J3").Value & "_" & "PAT"
Application.DisplayAlerts = False
MsgBox "Please select the folder to save PAT"
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
End With
ActiveWorkbook.saveas Filename:=File_Name & ".xlsm", FileFormat:=52
Application.DisplayAlerts = True
ActiveWorkbook.Close
Your challenge is that you're opening a file dialog, but not using the user's choice from that in the saveas. Try something along these lines:
Sub SaveFile()
Dim FolderName As String
File_Name = Format(Now(), "DDMMYYYY") & "_" & LName & EmpIN & "_" & Range("C6").Value & "_" & Range("J3").Value & "_" & "PAT"
Application.DisplayAlerts = False
MsgBox "Please select the folder to save PAT"
' Pop up the folder-selection box to get the folder form the user:
FolderName = GetFolder()
' If the user didn't select anything, you can't save, so tell them so:
If FolderName = "" Then
MsgBox "No folder was selected. Program will terminate."
Exit Sub
End If
' Create a path by combining the file and folder names:
File_Name = FolderName & "\" & File_Name & ".xlsm"
ActiveWorkbook.SaveAs Filename:=File_Name, FileFormat:=52
Application.DisplayAlerts = True
ActiveWorkbook.Close
End Sub
' A separate function to get the folder name and return it as a string
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Hope that helps.
In your code, you are not saving the path of the selected folder to a variable. In the code below, the path is saved to the variable selectedFolder, which gets its value from fldr.SelectedItems(1). Then the path + "\" + YourFileName & .xlsm is saved:
Option Explicit
Sub TestMe()
Dim fldr As FileDialog
Dim selectedFolder As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.Show
selectedFolder = .SelectedItems(1)
End With
ActiveWorkbook.SaveAs Filename:=selectedFolder & "\" & "YourFileName" & ".xlsm"
End Sub
Or alternatively, you may use a function, returning the folder's path from here:
VBA - Folder Picker - set where to start
A robust funciton, that I am using to GetFolder is this one:
Option Explicit
Sub myPathForFolder()
Debug.Print GetFolder(Environ("USERPROFILE"))
End Sub
Function GetFolder(Optional InitialLocation As String) As String
On Error GoTo GetFolder_Error
Dim FolderDialog As FileDialog
Dim SelectedFolder As String
If Len(InitialLocation) = 0 Then InitialLocation = ThisWorkbook.Path
Set FolderDialog = Excel.Application.FileDialog(msoFileDialogFolderPicker)
With FolderDialog
.Title = "My Title For Dialog"
.AllowMultiSelect = False
.InitialFileName = InitialLocation
If .Show <> -1 Then GoTo GetFolder_Error
SelectedFolder = .SelectedItems(1)
End With
GetFolder = SelectedFolder
On Error GoTo 0
Exit Function
GetFolder_Error:
Debug.Print "Error " & Err.Number & " (" & Err.Description & ")
End Function

Using VBA for attachments

I'm trying to use VBA to attach a file to an existing table but I keep running into a Runtime 3709 error as documented on the line below. I have a table with a few thousand files in it. What I would like to do is give the user the ability to select the file to be attached and when it's saved, the name will show up on the form. Any help would be appreciated. Thanks.
Dim rsParent As DAO.Recordset
Dim rsAttachment As DAO.Recordset2
Dim strFileName As String
Dim SQL As String
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.Title = "Choose the document to add to the form..."
.AllowMultiSelect = False
.InitialFileName = "C:\Users\"
If .Show = True Then
If .SelectedItems.Count = 0 Then
GoTo SubExit
End If ''
For Each varFile In .SelectedItems
strFileName = varFile
Next
Else
GoTo SubExit
End If
End With
SQL = "SELECT * FROM tblTable WHERE RecordID = " & Me.tbxRecordID
'Instantiate the parent recordset
Set rsParent = CurrentDb.OpenRecordset(SQL, dbOpenDynaset) ''
If rsParent.recordCount = 0 Then
MsgBox "There was a problem locating the selected record", vbCritical +
vbOKOnly, "Error"
GoTo SubExit
Else
' Put recordset in edit mode
rsParent.Edit
'Set the child recordset
Set rsAttachment = rsParent.Fields("Document").Value '**Runtime 3709 -
Search key not found**
'Add new attachment
rsAttachment.AddNew
rsAttachment.Fields("FileData").LoadFromFile strFileName
rsAttachment.Update
rsParent.Update
frmAttachments.Requery
End If
SubExit:
On Error Resume Next
If Not rsParent Is Nothing Then
rsParent.Close
Set rsParent = Nothing
End If
Exit Sub '
SubError:
MsgBox "Error Number: " & Err.Number & " = " & Err.Description, vbCritical + vbOKOnly, _
"An error occurred"
GoTo SubExit '
End Sub

MS Word 2013 VBA Macro Function

The following VBA Code will not save an open document to a sub-folder under the active 'My Documents' Folder. The code is called from App_DocumentBeforeClose and it executes without throwing a fault flag or process failed notification. All the code and save location string building works just the way its supposed to - the open document just doesn't get saved to the 'My Documents' sub-folder. The file itself is a working copy stored on a SDHC chip - could this be the problem? I have checked the folder rights and the sub-folder 'Read Only' attribute is turned off.
Public Sub SaveToTwoLocations()
Dim Res
Dim oDoc As Document, SourceFile As String, DestinationFile As String
Dim strBackUpPath As String, fDialog As FileDialog, Reps, DocName As String
If Right(ActiveWindow.Caption, 4) = "ode]" Then
DocName = Left(ActiveWindow.Caption, Len(ActiveWindow.Caption) - 21)
ElseIf Right(ActiveWindow.Caption, 5) = ".docx" Then
DocName = Left(ActiveWindow.Caption, Len(ActiveWindow.Caption) - 5)
End If
On Error GoTo CanceledByUser
Res = MsgBox("Save Source File?", vbQuestion + vbYesNo, "Save Original Prior to Back-Up Interrogative")
If Res = vbYes Then
Application.ActiveDocument.Save
End If
If GetSetting("My_Books", DocName, "Save_2") = "" Then
Set fDialog = Application.FileDialog(msoFileDialogFolderPicker)
With fDialog
.Title = "Select Folder to Save The Copy To & Click Ok"
.AllowMultiSelect = False
.InitialView = msoFileDialogViewList
If .Show <> -1 Then
MsgBox "Canceled By user", , "Save To Two Locatiions"
Exit Sub
End If
strBackUpPath = fDialog.SelectedItems.Item(1) & "\"
Res = MsgBox("Save File To Selected 'SaveTo' Location?", vbQuestion + vbYesNo, "'SaveTo' Interrogative")
If Res = vbYes Then
SaveSetting "My_Books", DocName, "Save_2", strBackUpPath
strBackUpPath = strBackUpPath & DocName & ".docx"
Application.ActiveDocument.SaveAs2 (strBackUpPath)
Else
Exit Sub
End If
End With
Else
strBackUpPath = GetSetting("My_Books", DocName, "Save_2")
Res = MsgBox("Save This Document To: " & strBackUpPath & "?", vbQuestion + vbYesNo, "Two Location Save Interrogative")
If Res = vbYes Then
If Right(ActiveDocument.Name, 1) = "x" Then
Application.ActiveDocument.SaveAs2 (strBackUpPath = strBackUpPath & DocName & ".docx")
Else
MsgBox "Non-docx Doument File Save Error", vbCritical, "2nd Location File Save Error"
GoTo CanceledByUser
End If
Else
Set fDialog = Application.FileDialog(msoFileDialogSaveAs)
With fDialog
.Title = "Select Folder to Save The Copy To & Click Ok"
.AllowMultiSelect = False
.InitialView = msoFileDialogViewList
If .Show <> -1 Then
MsgBox "File Save Canceled By User", , "Save To Two Locatiions Canceled"
Exit Sub
End If
End With
End If
End If
CanceledByUser:
End Sub
Application.ActiveDocument.SaveAs2 (strBackUpPath = strBackUpPath & DocName & ".docx")
should be
Application.ActiveDocument.SaveAs2 strBackUpPath
The code should have been: Application.ActiveDocument.SaveAs2 (strBackUpPath & DocName & ".docx") In my defense, I will say that Microsoft is often its own worst enemy for reasons amply documented elsewhere - as for the code as originally written, it would have worked in standard VB6, BUT VBA is not VB6. To Tim Williams I offer my thanks - while technically incorrect, you put me on to the right answer, AND it's possible the concatenation, as written was being misinterpreted by the compiler. But the concatenation as rewritten was still required for reasons of efficiency and compactness. Oh, and it's working perfectly now that i have corrected my mistake! Thanks to all!