I am trying to create a block of code that allows one to receive the name of an unknown workbook, and reference data from it. Referencing by index number doesn’t seem like a viable option as users will often have other workbooks out at the same time. The unknown workbook is already open, but I need to retrieve its name. I am using a FileDialog to allow the user to select the desired workbook, save the filepath as a string, then use it to reference the workbook.
When I attempt to reference the workbook, I get a Subscript Out of Range error. Directly inputting the name of the workbook instead of a variable worked just fine, but attempting to use a variable didn’t work. I tried using quotes, no quotes, and double quotes, but the error remained the same.
Here is my code. What exactly was I doing wrong?
Sub ObtainExternalWorkbook()
'Declare variables
Dim filepath As String
Dim WK As FileDialog
Set WK = Application.FileDialog(msoFileDialogFilePicker)
'Acquire file name.
MsgBox ("Please select the desired file to be used.")
With WK
.AllowMultiSelect = False
.Title = "Select the desired file."
If .Show = False Then
Exit Sub
End If
filepath = .SelectedItems.Item(1)
End With
'Use file name to activate workbook.
Workbooks(" & filepath & ").Activate
End Sub