我正在使用以下函数从其他工作簿中提取数据。
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)
之前以某种方式激活工作簿。我怎么做?我计划使用此函数从大约数百个工作簿中提取数千个单元格,以帮助我尽可能高效地使用此代码。谢谢!
答案 0 :(得分:1)
我认为您正在寻找的是(从您的代码中修改):
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
else
CurrBook = Workbooks.Open Path & File
End If
'''Code here
CurrBook.Close
这将打开文件,如果已找到,您将能够从中提取数据。我希望这有帮助!
答案 1 :(得分:0)
这有效
Function GetValue(path, file, sheet, ref)
'Retrieves a value from a closed workbook
Dim myArg As String
Dim CurrBook As Workbook
'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
Application.Workbooks.Open (path & file)
'Create the argument
myArg = "'" & path & "[" & file & "]" & sheet & "'!" & Range(ref).Range("A1").Address(, , xlR1C1)
'Execute an XLM macro
GetValue = ExecuteExcel4Macro(myArg)
Application.Workbooks(file).Close (False)
End Function
答案 2 :(得分:0)
如果您打算打开工作簿,则根本不需要执行exeteexcel4macro:
Function GetValue(path, file, sheet, ref)
Dim CurrBook As Workbook
'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
Set CurrBook = Application.Workbooks.Open(path & file)
On Error Resume Next
GetValue = CurrBook.Sheets(sheet).Range(ref).Value
CurrBook.Close savechanges:=False
End Function