1

我在看这个链接的帖子: http: //spreadsheetpage.com/index.php/site/tip/a_vba_function_to_get_a_value_from_a_closed_file/

功能是

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

并获得一个价值,

Sub TestGetValue()
    p = "c:\XLFiles\Budget"
    f = "Budget.xls"
    s = "Sheet1"
    a = "A1"
    MsgBox GetValue(p, f, s, a)
End Sub

并循环

Sub TestGetValue2()
    p = "c:\XLFiles\Budget"
    f = "Budget.xls"
    s = "Sheet1"
    Application.ScreenUpdating = False
    For r = 1 To 100
        For c = 1 To 12
            a = Cells(r, c).Address
            Cells(r, c) = GetValue(p, f, s, a)
        Next c
    Next r
    Application.ScreenUpdating = True
End Sub

我觉得写得非常好。但是,我遇到了两个问题:

  1. 如果关闭文件中的源单元格为空白(VBA 中的“”),我会在 getvalue 中得到 0。

我想知道如何将 0 传递给 0 并将“”传递给“”?
有错误ExecuteExcel4Macro吗?

  1. 假设源文件具有不同的扩展名:xls、xlsx、xlsm 或 xlsb,... 如何获得动态路径?

我试图消除路径中的文件扩展名并使用

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

但是,它在ExecuteExcel4Macro.

4

1 回答 1

1

这是正常的 Excel 行为。如果将公式放入单元格 A1

=B1

那么 A1 也会显示一个 0

您可以使用以下代码获取值:

Public Function GetValue(sFileName As String, sSheetName As String, sAddress As String) As Variant

    Dim oSheet As Worksheet

    Application.ScreenUpdating = False

    With Workbooks.Add(sFileName)
        GetValue = .Sheets(sSheetName).Range(sAddress).Value
        .Close
    End With

    Application.ScreenUpdating = True

End Function
于 2015-09-23T21:44:16.130 回答