I am a new Excel 2013 vba programmer. I have written code to loop through each file in a folder, open it, copy the cells, and paste to a new file, increment down a row, and do this for each file in the folder.
Before I loop to the next file, I close the previous one. There are about 120 files in the folder. This is ultimately to create an index of the data in the folder in a single file.
This seems to run fine when I "step through", but if I just F5 the macro it runs for a while, I see it working fine, and then part way through it crashes Excel "Excel has stopped working..." it just shuts down.
Have you ever run into this before? Any suggestions? Here's the subset of the code that does the work:
Sub WorkHorse()
' Application.DisplayAlerts = False 'large amount of data in clipboard, do you want to keep..." message_ *MUST TURN BACK ON SEE BELOW!!
ChDir "R:\ISO\Sticks\307M"
myFile = Dir("*.xlsx")
Do Until myFile = ""
Workbooks.Open Filename:=myFile
If Range("A3") = "" Then
Range("A2").Select
Range(Selection, Selection.End(xlToRight)).Select
End If
If Range("A3") <> "" Then
Range("A2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
End If
Selection.Copy
Windows("Test for Possanza Aug 2015.xlsm").Activate
ActiveSheet.Paste
Range("A1").Select
ActiveSheet.Range("A1").Copy
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Range("a1").Select
Windows(myFile).Close
myFile = Dir
Loop
' Application.DisplayAlerts = True 'this re-enables Display Alerts in MSOffice. *CRITICAL TO TURN BACK ON!
End Sub
Hi everyone thanks for the help. Feel free to advise me on how to add new code with additional comments/questions -- this is new to me.
Per my comment below and your suggestions I have modified the code. I haven't tried it with Davesexcel's fix yet, but when it didn't work yesterday I did some digging and found a CurrentRegion command that seems to work except it includes the header line (row 1) from each of the files being copied. The information I found said it assumes a header row and does not include it, but that doesn't seem to be happening. Here's my new code, suggestions very much appreciated. ALSO, the one commented line -- why doesn't that work? it errors out. I was trying to be specific regarding workbook and worksheet (always the first worksheet in the workbook, but name varies), per the suggestions you pointed me to. Thanks.
Sub ReDoWorkHorseWithoutSelect()
Dim myfile As String
Dim wb As Workbook
Dim ws As Worksheet
Dim DataBlock As Range
Set wb = Workbooks("Test for Possanza Aug 2015.xlsm")
Set ws = wb.Sheets("Sheet1") 'change desired sheet
ChDir "R:\ISO\Sticks\307M"
myfile = Dir("*.xlsx")
Do Until myfile = ""
Workbooks.Open Filename:=myfile
' Set DataBlock = Workbooks("myfile").Worksheets(1).Range("A1").CurrentRegion
Set DataBlock = Range("A2").CurrentRegion
DataBlock.Copy ws.Cells(ws.Rows.Count, "A").End(xlUp).Offset(1)
Windows(myfile).Close
myfile = Dir
Loop