【问题标题】:Get Workbook reference from Open File dialog从“打开文件”对话框获取工作簿参考
【发布时间】:2016-09-14 08:04:39
【问题描述】:

我正在使用 Excel 2013 宏从用户选择的工作簿中提取数据,而我的 vba 有点生疏了。

Application.GetOpenFilename 提示用户输入文件位置,打开文件并返回一个字符串。 Workbooks.Open(string) 返回工作簿 - 如果您事先知道名称。

我想结合这些来询问用户要打开哪个文件,并返回一个工作簿。

根据 Frank 在此处的回答 (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 文件,并将对它的引用作为工作簿返回?

【问题讨论】:

  • 试试我下面回答中的代码

标签: excel excel-2013 vba


【解决方案1】:

试试下面的代码:

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

【讨论】:

  • 已售出!有趣的是,我不能做最初提出这个问题的Workbooks("nameFromFileDialog").Activate。我期待Workbooks(workbookReference).Activate 工作,但似乎我需要Workbooks(workbookReference.Name).Activate。所以现在我不明白为什么我最初尝试的字符串不起作用,但工作簿名称字符串确实......(但我不会为此失眠:)
【解决方案2】:

看起来你还没有显示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

【讨论】:

  • 我的代码确实显示了 FileDialog。我认为使用 .show 的原因是看 filedialog 是返回 true 还是 false。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多