我正在尝试编写一个宏,以特定顺序将数据从多个外部工作簿复制到单个工作簿。我不打算让每个工作簿都为我的宏工作而打开,因为这将是一个非常多的打开电子表格,所以我进行了谷歌搜索并遇到了这个漂亮的函数,即 GetValue 函数: http://spreadsheetpage。 com/index.php/tip/a_vba_function_to_get_a_value_from_a_closed_file/
只是为了为其余代码做好准备,我编写了一个代码,该代码应该只是从外部工作簿的单元格中获取一条数据,并将其放入工作簿和工作表的单个单元格中目前在。在当前工作表中,我将要访问的工作簿的文件路径粘贴到 B 列中,以及 A 列中的文件名,因为有这么多,我希望能够一次访问每个代码。这是该代码:
Sub Gather_Data()
Dim p As String
Dim f As String
Dim s As String
Dim a As String
p = Range("B7").Value
f = Range("A7").Value
s = Sheet5
a = D7
Cells(10, 10).Value = GetValue(p, f, s, a).Value
End Sub
Private Function GetValue(path, file, sheet, ref)
' Retrieves a value from a closed workbook
Dim arg As String
' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
' Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
End Function
我看不出代码有什么问题,但是每当我尝试运行它时,我都会收到一个运行时错误,指出“对象'_Global'的方法'范围'失败”。老实说,我不知道这意味着什么,运行调试器会突出显示
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
区域,我什至没有写。如果有人有使用此功能的经验或知道如何解决此错误,我们将不胜感激。提前致谢!