我们有三个文件,文件1和文件1 2包含工作表1中的数据。在文件3中,工作表2有一个按钮和一个表(包含文件1和2的详细信息,如文件名和路径):
File 1
ABC 123
File 2
BAC 321
单击工作表2上的按钮后,宏应该从文件1和2的工作表1中获取数据,并将它们放在文件3的工作表1中,如下所示: -
File 3
ABC 123
BAC 321
我发现使用以下功能执行相同操作的代码很少,但它们只能在代码所在的工作表中使用。
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
' Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
答案 0 :(得分:1)
这是您尝试做的一个很好的链接。 Get info from closed file
以下是一些可以帮助您入门的代码。现在,它设置为从sheet2'A1'获取第一个文件路径,从'A2'获取工作簿名称,并将值返回到sheet1'A1'。一旦你完成这项工作,你将需要遍历你的范围(取决于你如何设置)并显示结果。
Sub ReadDataFromAllWorkbooksInFolder()
Dim FolderName As String, wbName As String, r As Long, cValue As Variant
Dim wbList() As String, wbCount As Integer, i As Integer
'Path from sheet two in macro book
FolderName = Worksheets(2).Range("A1").Text
'File Name from sheet two in macro book
Filename = Worksheets(2).Range("A2").Text
wbName = Worksheets(2).Range("A2").Text
cValue = GetValue(FolderName, wbName, "Sheet1", "A1")
Worksheets(1).Cells(1, 1).Formula = cValue
End Sub
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 XLM macro
GetValue = ExecuteExcel4Macro(Arg)
End Function