我在这个链接上看了一篇帖子: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有错误吗?
2.假设源文件有不同的扩展名:xls,xlsx,xlsm或xlsb,... 我怎样才能获得动态路径?
我试图消除路径中的文件扩展名并使用
arg = "'" & path & "[" & file & ".xl?]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
但是,它在ExecuteExcel4Macro中不起作用。
答案 0 :(得分: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