【发布时间】:2014-07-02 11:59:59
【问题描述】:
我正在使用下面的函数从其他工作簿中提取数据。
Function GetValue(path, file, sheet, ref)
'Retrieves a value from a closed workbook
Dim myArg 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
myArg = "'" & path & "[" & file & "]" & sheet & "'!" & Range(ref).Range("A1").Address(, , xlR1C1)
'Execute an XLM macro
GetValue = ExecuteExcel4Macro(myArg)
End Function
我这样调用这个函数:
Sub TestGetValue()
Dim p As String, f As String
Dim s As String, a As String
p = "C:\Users\schaudha\Desktop\FIT transition\test simulation results"
f = "all cancer rate.xml"
s = "CONTENTS"
a = "A1"
MsgBox GetValue(p, f, s, a)
End Sub
此功能似乎仅在工作簿处于活动状态时才有效。我的意思是,如果我打开需要从中获取数据的 Excel 文件,然后运行我的子程序,它可以工作,但如果它关闭,它就不起作用。我也希望它在工作簿关闭时工作。我猜我需要在使用ExecuteExcel4Macro(myArg) 之前以某种方式激活工作簿。我怎么做?我计划使用这个函数从大约一百个工作簿中从数千个单元格中提取数据,所以我想让这段代码尽可能高效。
【问题讨论】:
-
设置 oSpreadsheet = Workbooks.Open(Filename:=path & file)
-
您的工作簿不是 Excel 工作簿,而是 XML 文件,这就是代码不起作用的原因。您必须将文件作为工作簿实际打开,或者使用不同的方法来解析 XML 内容。