I am trying to copy a line of data from several workbooks in a folder and paste them into a master workbook (in the same folder) using VBA for Excel 2011 Mac. I have the following code but continually run into a Runtime error 1004
.
After debugging it highlights the Workbooks.Open(MyFile)
line but I can't figure out why. The path is correct. Can anyone please advise on what is wrong?
I got the original code from http://www.familycomputerclub.com/transfer-data-from-multiple-workbooks-into-master-workbook-automatically-using-vba.html which is for Windows. Any info would be greatly appreciated!
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
You are using MyFile = ("/Users/administrator/Desktop/Excel")
(why the parentheses by the way?), but that is not actually a valid path to a workbook, right?
I mean, surely it should point to a .xlsm file and not just to a directory... That should be what gives you the error.
I think you need to find all the workbooks in your directory first and then loop through those. The way your code is written now seems really wrong to me, but of course that doesn't mean it won't work. But I really think you need to parse the directory for .xlsm files first and then loop through those.
UPDATE
I think this code should now do what you want.
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
But you will have to modify the starting directory path directory
, as well as the logic in the With
End With
block to suit your needs.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.