【问题标题】:How Do I Resolve Run-Time Error With GetValue Function in Excel VBA?如何使用 Excel VBA 中的 GetValue 函数解决运行时错误?
【发布时间】:2017-06-22 19:40:18
【问题描述】:

我正在尝试编写一个宏,它可以按特定顺序将数据从多个外部工作簿复制到单个工作簿。我不打算让每个工作簿都为我的宏工作而打开,因为这将是一个非常多的打开电子表格,所以我进行了谷歌搜索并遇到了这个漂亮的函数 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' 的方法 'Range' 失败”。老实说,我不知道这意味着什么,运行调试器会突出显示

    arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
      Range(ref).Range("A1").Address(, , xlR1C1)

区域,我什至没有写。如果有人有使用此功能的经验或知道如何解决此错误,我们将不胜感激。提前致谢!

【问题讨论】:

    标签: vba excel function getvalue


    【解决方案1】:

    你的变量被声明为字符串,所以试着改变你的代码:

    s = Sheet5
    a = D7
    

    到这里:

    s = "Sheet5"
    a = "D7"
    

    【讨论】:

    • 谢谢!我应该能够自己嗅出它......哎呀。
    猜你喜欢
    • 2021-09-11
    • 2015-11-18
    • 2019-03-01
    • 2016-11-08
    • 2019-12-15
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2016-11-09
    相关资源
    最近更新 更多