Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
```vb
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
MyFile = Dir("C:\Users\SJPM\Desktop\Sal\")
Do While Len(MyFile) > 0
If MyFile = "zmaster.xlsm" Then
Exit Sub
End If
Workbooks.Open (MyFile)
Worksheets("Final Salary").Range("B22:E32").Copy
ActiveWorkbook.Save
ActiveWorkbook.Close
erow = ActiveWorksheets.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveWorksheets.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 4))

MyFile = Dir

Loop
End Sub
```
Posted
Updated 5-Apr-15 23:50pm
v2
Comments
Richard MacCutchan 6-Apr-15 5:49am    
What is your question?
Member 10885804 6-Apr-15 5:51am    
I Found run time error no 1004 when I compiling this code pl. help me
Richard MacCutchan 6-Apr-15 5:54am    
Where? What does runtime error 1004 mean?
Member 10885804 6-Apr-15 5:57am    
The full form of this error is this "Application-defined or object-defined error"
I do not know what is this I am running this code in excel vba platform
Richard MacCutchan 6-Apr-15 6:01am    
I suggest you use the VBA debugger to step through the code to see where the error occurs. At a guess it could be something to do with trying to reference worksheet data after closing the workbook.

1 solution

The error occurs in this line:
VB
Workbooks.Open (MyFile)

because MyFile contains only file name without its path!

Try this:
VB
Sub LoopThroughDirectory()
Dim sFile As String, sPath As String, eRow as Integer
Dim srcWbk As Workbook, dstWbk as Workbook
Dim srcWsh As Worksheet, dstWsh as Worksheet 

Set dstWbk = ThisWorkbook
Set dstWsh = dstWbk.Worksheets("Sheet1")

sPath = "C:\Users\SJPM\Desktop\Sal\"
sFile = Dir(sPath)
Do While sFile<>""
    If MyFile = "zmaster.xlsm" Then
        Exit Do
    End If
    Set srcWbk = Application.Workbooks.Open(sPath & MyFile)
    Set srcWsh = Worksheets("Final Salary")
    eRow = dstwsh.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    srcWsh.Range("B22:E32").Copy dstWsh.Range(Cells(erow, 1), Cells(erow, 4))
    srcWbk.Close SaveChanges:=False
    MyFile = Dir()
Loop

'close destination workbook
dstWbk.Close SaveChanges:=True

End Sub


Note: you have to change above code to your needs!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900