0

我正在尝试从文件夹中的多个工作簿中复制一行数据,然后使用 VBA for Excel 2011 Mac 将它们粘贴到主工作簿(在同一文件夹中)。我有以下代码,但不断遇到Runtime error 1004.

调试后它突出显示该Workbooks.Open(MyFile)行,但我不知道为什么。路径是正确的。任何人都可以请教什么是错的?

我从http://www.familycomputerclub.com/transfer-data-from-multiple-workbooks-into-master-workbook-automatically-using-vba.html获得了适用于 Windows 的原始代码。任何信息,将不胜感激!

Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
MyFile = ("/Users/administrator/Desktop/Excel")

Do While Len(MyFile) > 0
    If MyFile = "Test.xlsm" Then
    Exit Sub
    End If

    Workbooks.Open (MyFile)
    Range("A2:D2").Copy
    ActiveWorkbook.Close

    erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 4))

    MyFile = Dir

Loop

End Sub
4

1 回答 1

0

您正在使用MyFile = ("/Users/administrator/Desktop/Excel")(为什么要使用括号?),但这实际上不是工作簿的有效路径,对吧?

我的意思是,它当然应该指向一个 .xlsm 文件,而不仅仅是一个目录......这应该是给你错误的原因。

我认为您需要先找到目录中的所有工作簿,然后再遍历它们。您现在编写代码的方式对我来说似乎确实是错误的,但这当然并不意味着它不起作用。但我真的认为你需要先解析 .xlsm 文件的目录,然后循环遍历这些文件。

更新

我认为这段代码现在应该做你想做的事。

Sub LoopThroughFiles()

Dim directory As String
Dim file As Variant

directory = "C:\Users\RISE123\Desktop\NSRP\AFPR004\Foundations\20140702 - AFPR004 FA9 Change\"
file = Dir(directory)

Do While Len(file) > 0
    If InStr(1, file, ".xlsm", vbBinaryCompare) > 0 Then
        With Workbooks.Open(directory & file)
            Call .Worksheets(1).Range("A2:D2").Copy(ThisWorkbook.Sheets(1).Range("A2:D2"))
            Call .Close(False)
        End With
    End If
    file = Dir
Loop

End Sub

但是您必须修改起始目录路径directory以及With End With块中的逻辑以满足您的需要。

于 2014-07-30T04:44:33.870 回答