I have the FilePicker for choosing my Excel file. Unfortunately with the following code:
Option Explicit
Sub Select_form()
Dim FilePicker As FileDialog
Dim mypath As String
Dim formwb As Workbook
Set FilePicker = Application.FileDialog(msoFileDialogFilePicker)
With FilePicker
.Title = "Please select the hazard form"
.AllowMultiSelect = False
.ButtonName = "Confirm selection"
If .Show = -1 Then
mypath = .SelectedItems(1)
Else
End
End If
End With
Set formwb = openDataFile
Debug.Print formwb.Name
End Sub
Function openDataFile() As Workbook
' Dim wb As Workbook Dim filename As String Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Select the file to extract data"
' Optional properties: Add filters
fd.Filters.Clear
fd.Filters.Add "Excel files", "*.xls*" ' show Excel file extensions only
' means success opening the FileDialog
If fd.Show = -1 Then
filename = fd.SelectedItems(1)
End If
' error handling if the user didn't select any file
If filename = "" Then
MsgBox "No Excel file was selected !", vbExclamation, "Warning"
End
End If
Set openDataFile = Workbooks.Open(filename)
End Function
The filedialog opens twice.
I tried these hints:
https://www.mrexcel.com/board/threads/how-to-use-multiple-directories-using-vba.922514/
https://bytes.com/topic/access/answers/959014-file-dialog-runs-twice
but with no results
FileDialog
ObjectSub Select_form()
Dim formwb As Workbook: Set formwb = OpenExcelFile
If formwb Is Nothing Then Exit Sub
' Continue using 'formwb' e.g.:
MsgBox "Just opened workbook """ & formwb.Name & """ located in """ _
& formwb.Path & """.", vbInformation
End Sub
Function OpenExcelFile() As Workbook
Const PROC_TITLE As String = "Open Excel File"
Dim ErrorMsgString As String
On Error GoTo ClearError
Dim FilePath As String
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "Select the file to extract data"
.Filters.Clear
.Filters.Add "Excel files", "*.xls*"
If .Show = -1 Then FilePath = .SelectedItems(1)
End With
If Len(FilePath) = 0 Then
MsgBox "Dialog canceled!", vbExclamation, PROC_TITLE
Else
Set OpenExcelFile = Workbooks.Open(FilePath)
End If
Exit Function
ProcExit:
On Error Resume Next
MsgBox ErrorMsgString, vbCritical, PROC_TITLE
On Error GoTo 0
Exit Function
ClearError:
ErrorMsgString = "Run-time error '" & Err.Number & vbLf & vbLf _
& Err.Description
Resume ProcExit
End Function