Add Header When Merging Data from Multiple Workbooks/Worksheets

BenChod

New Member
Joined
Jun 1, 2017
Messages
1
Hello All -

I have multiple worksheets from multiple workbooks where I want to append data into a master worksheet. Each worksheet will have the same headers and when appending, I want the header on the top row and the data from the worksheets to append without their headers. The code will copy from the second row until the end (sans the header). The code is copied below. I added a line code at the end to insert a row and then copy the header and it's not working. I am hoping someone can take a quick look and tell me what I am doing wrong. Thanks for your help.

Sub Basic_Example_2()
Dim MyPath As String
Dim SourceRcount As Long, Fnum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
Dim SaveDriveDir As String
Dim FName As Variant
Dim FirstCell As String




'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With


SaveDriveDir = CurDir
ChDirNet "C:\Data\Test"


FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
MultiSelect:=True)
If IsArray(FName) Then


'Add a new workbook with one sheet
Set BaseWks = ThisWorkbook.Worksheets("QC")
rnum = 1




'Loop through all files in the array(myFiles)
For Fnum = LBound(FName) To UBound(FName)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(FName(Fnum))
On Error GoTo 0


If Not mybook Is Nothing Then


On Error Resume Next
With mybook.Worksheets(1)
FirstCell = "A2"
Set sourceRange = .Range(FirstCell & ":" & RDB_Last(3, .Cells))
'Test if the row of the last cell >= then the row of the FirstCell
If RDB_Last(1, .Cells) < .Range(FirstCell).Row Then
Set sourceRange = Nothing
End If
End With




If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
'if SourceRange use all columns then skip this file
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0


If Not sourceRange Is Nothing Then


SourceRcount = sourceRange.Rows.Count


If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "Sorry there are not enough rows in the sheet"
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else


'Copy the file name in column A
With sourceRange
BaseWks.Cells(rnum, "A"). _
Resize(.Rows.Count).Value = FName(Fnum)
End With


'Set the destrange
Set destrange = BaseWks.Range("B" & rnum)


'we copy the values from the sourceRange to the destrange
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value


rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If


Next Fnum
BaseWks.Columns.AutoFit
End If






ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
ChDirNet SaveDriveDir

Range("A1").EntireRow.Insert
'Copy header row, change the range if you use more columns
If WorksheetFunction.CountA(BaseWks.UsedRange) = 0 Then
sourceRange.Range("A1:Z1").Copy BaseWks.Range("A1")


End If
End Sub
 

Excel Facts

Can Excel fill bagel flavors?
You can teach Excel a new custom list. Type the list in cells, File, Options, Advanced, Edit Custom Lists, Import, OK
BenChod,

Welcome to the Board.

Code:
If WorksheetFunction.CountA(BaseWks.UsedRange) = 0 Then 
              sourceRange.Range("A1:Z1").Copy BaseWks.Range("A1") 
    End If

This line - "If WorksheetFunction.CountA(BaseWks.UsedRange) = 0" - will likely be > 0 if you've been copying data to the BaseWks sheet. And since you're inserting a Row at Row 1, there's no need to check if it contains any data; by default it'll be blank.

So you only need the line - "sourceRange.Range("A1:Z1").Copy BaseWks.Range("A1")" - but since you've already closed the workbook that contains the sourceRange there's nothing to copy.

Cheers,

tonyyy
 
Upvote 0
Range("A1").EntireRow.Insert
'Copy header row, change the range if you use more columns
If WorksheetFunction.CountA(BaseWks.UsedRange) = 0 Then
sourceRange.Range("A1:Z1").Copy BaseWks.Range("A1")
Since you have close all your source workbooks, this code will not work at the point where you have it. It will not find sourceRange, which is the wrong variable to reference to begin with. You want to get the source workbook and sheet reference which are parent to Range("A1:Z1") for it to work. I think I would move the header code to just after the workbooks.Open statement with something like this
Code:
If BaseWks.Sheets(1).Range("A1").Value <> mybook.Sheets(1).Range("A1").Value Then
    If Application.CountA(BaseWks.Range("1:1") > 0 Then
         BaseWks.Rows(1).Insert
         mybook.Sheets(1).Rows(1).Copy BaseWks.Range("A1")
    Else
         mybook.sheets(1).Rows(1).Copy BaseWks.Range("A1")
    End If 
End If
That way your headers will be inserted starting with the first source file.
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,606
Messages
6,120,484
Members
448,967
Latest member
visheshkotha

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top