我正在使用Excel 2013宏从用户选择的工作簿中提取数据,而我的vba有点生锈。
Application.GetOpenFilename
提示用户输入文件位置,打开文件并返回一个字符串。 Workbooks.Open(string)
会返回一个工作簿 - 如果您事先知道该名称。
我想将这些组合起来询问用户打开哪个文件,然后返回工作簿。
基于弗兰克在这里的回答(Open a workbook using FileDialog and manipulate it in Excel VBA)我试过这个:
Function openDataFile() As Workbook
'
Dim wb As Workbook
Dim filename As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Select the file to extract data"
'filename = fd.SelectedItems(1)
Set wb = Workbooks.Open(fd.SelectedItems(1))
openDataFile = wb
End Function
但这会落在Run-time error '5': Invalid procedure call or argument.
如何提示用户打开excel文件,并将其作为工作簿返回?
答案 0 :(得分:2)
尝试以下代码:
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
然后我在下面添加了Sub来测试这个功能:
Sub test()
Dim testWb As Workbook
Set testWb = openDataFile
Debug.Print testWb.Name
End Sub
答案 1 :(得分:0)
看起来你还没有显示FileDialog
所以可能是这样的:
Function openDataFile() As Workbook
'
Dim wb As Workbook
Dim filename As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Select the file to extract data"
fd.show
On Error Resume Next ' handling error over the select.. later in the script you could have an `if fileName = "" then exit sub` or something to that affect
fileName = fd.SelectedItems(1)
On Error GoTo 0
Set wb = Workbooks.Open(fileName)
openDataFile = wb
End Function