How to Merge Data from Two Excel Worksheets

How to merge data from Two Excel worksheets in a new workbook and create a new database using Microsoft Query. We also record the macro while we are performing the actions to merge the data from the two worksheets in a new file. We then edit the recorded code and finally  assign the macro to a button control. If you now enter more data into your database in the student-data file and run the macro again the new data will also be incorporated into the database. Watch the video below:


Watch this video on YouTube.

Here’s the complete VBA code to merge data to create new database:

Sub Macro1()

‘ Macro1 Macro

Application.CutCopyMode = False
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array(Array( _
“ODBC;DSN=Excel Files;DBQ=C:\Users\takyar\Desktop\student-data.xlsx;DefaultDir=C:\Users\takyar\Desktop;DriverId=1046;MaxBufferSize=20” _
), Array(“48;PageTimeout=5;”)), Destination:=Range(“$A$1”)).QueryTable
‘.CommandType = 0
.CommandText = Array( _
“SELECT `Sheet1$`.ID, `Sheet1$`.`First Name`, `Sheet1$`.`Last Name`, `Sheet2$`.`Attendance %`, `Sheet2$`.`Marks %`” & Chr(13) & “” & Chr(10) & “FROM `C:\Users\takyar\Desktop\student-data.xlsx`.`Sheet1$` `Sheet1$`, `C:\Users\takya” _
, _
“r\Desktop\student-data.xlsx`.`Sheet2$` `Sheet2$`” & Chr(13) & “” & Chr(10) & “WHERE `Sheet1$`.ID = `Sheet2$`.ID” _
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = “Table_Query_from_Excel_Files”
.Refresh BackgroundQuery:=False
End With
End Sub

While entering the code we should be careful about the quotes and apostrophes otherwise we will get errors.


Published by

Dinesh Kumar Takyar

Welcome to! My aim is to help you learn MS Excel including VBA. I always felt that a good way to learn something was to find solutions to problems in that domain. That is why I share these Excel videos with you. Mostly these are questions asked during my corporate training sessions. I've been training individuals and companies in computers since 1991. I did my B. Sc. (Vordiplom), M. Sc. (Diplom) and Ph.D. (Dr. rer. nat.) from Hamburg, Germany. The best thing about solving some of my visitor's questions is that I also gain new insights. For more Excel VBA solutions you may like to visit my YouTube channel: For a structured Excel VBA training course online you can visit:

One thought on “How to Merge Data from Two Excel Worksheets”

Leave a Reply

Your email address will not be published. Required fields are marked *