I am running the code line-by-line. It is going through the code fine and copying data from each book and pasting it into the MasterCombine workbook. However, when it gets the last workbook, everything is deleted and it reverts back to the original file with original data. It appears to be crapping out when it gets to command that opens file.
'Open file
Set wbkOld = Workbooks.Open(fName)
I can't for the life of me figure out what is wrong. Any help is appreciated. I am trying the code in Excel 2003.
I have all the data in one path, which is "G:\Excel Tips\Combine Workbooks\WorkbookData\" The files are:
Book1
Book2
Book3
Book4
Book5
MasterCombine (contains code to combine Book 1-5)
I have another path, which is "G:\Excel Tips\Combine Workbooks\WorkbookData\Import\"
This folder is empty.
Sub Consolidate()
'Author: JBeaucaire'
'Date: 9/15/2009 (2007 compatible)'
'Summary: Open all Excel files in a specific folder and merge data'
' into one master sheet (stacked)'
' Moves imported files into another folder'
Dim fName As String, fPath As String, fPathDone As String, OldDir As String
Dim LR As Long, NR As Long
Dim wbkOld As Workbook, wbkNew As Workbook, ws As Worksheet
'Setup
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Set wbkNew = ThisWorkbook
wbkNew.Activate
Sheets("Master").Activate 'sheet report is built into...edit to match
If MsgBox("Import new data to this report?", vbYesNo) = vbNo Then Exit Sub
If MsgBox("Clear the old data first?", vbYesNo) = vbYes Then
Range("A2:A" & Rows.Count).EntireRow.ClearContents
NR = 2
Else
NR = Range("A" & Rows.Count).End(xlUp).Row + 1
End If
'Path and filename
OldDir = CurDir 'memorizes the user's current working path
fPath = "G:\Excel Tips\Combine Workbooks\WorkbookData\"
fPathDone = "G:\Excel Tips\Combine Workbooks\WorkbookData\Imported\" 'optional
ChDir fPath
fName = Dir("*.xl*") 'filtering key, change to suit
'Import a sheet from found file
Do While Len(fName) > 0
'Open file
Set wbkOld = Workbooks.Open(fName)
'Find last row and copy data
Sheets(1).Activate
LR = Range("A" & Rows.Count).End(xlUp).Row 'find the bottom row of data...change to a different column if "A" isn't reliable for spotting this value
Range("A2:A" & LR).EntireRow.Copy _
wbkNew.Sheets("Master").Range("A" & NR)
'close file
wbkOld.Close False
'Next row
NR = Range("A" & Rows.Count).End(xlUp).Row + 1
'move file to "imported" folder
Name fPath & fName As fPathDone & fName 'optional
'ready next filename
fName = Dir
Loop
'Cleanup
ActiveSheet.Columns.AutoFit
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
'restores user's original working path
ChDir OldDir
End Sub
Bookmarks