从封闭的文件中获取一个值

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

function是

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.如果closures文件中的源单元格是空的(VBA中的“”),则getvalue中的值为0。

我不知道如何可以传递0到0,并通过“”到“”?
ExecuteExcel4Macro有错误吗?

2.假设源文件具有不同的扩展名:xls,xlsx,xlsm或xlsb,…我如何获得dynamicpath?

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

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

但是,它在ExecuteExcel4Macro中不起作用。

这是正常的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