Reputation: 315
I am not sure what approach to take but wondering can I join data from two excel sheets and populate in a 3rd sheet like how we join in SQL using VBA. Example data is below, I would like to join Sheet1 and Sheet2 by Emp_id and populate the result in Sheet3. I have googled a lot and tried whatever I know but nowhere I am close to get this, can someone throw some light on this or share an working example, that would be great. I am still trying and will post if I got a solution.
Upvotes: 2
Views: 5931
Reputation: 417
cn As New ADODB.Connection
rec As New ADODB.Recordset
cn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & _
ActiveWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
SQLquery = "SELECT [Sheet2$].[Emp_id],[Sheet2$].[Hobies],[Sheet1$].[Salary] FROM [Sheet2$] INNER JOIN [Sheet1$] ON [Sheet2$].[Emp_id]=[Sheet1$].[Emp_id]"
rec.Open SQLquery, cn, adOpenKeyset, adLockOptimistic
Sheets("Sheet3").Range("A1").CopyFromRecordset rec
Upvotes: 0
Reputation: 315
Below works for mine, again below query is for the sample data. For my actual data, I had to get the sheet number to use sheet name (example [Sheet2$] is replaced with [Sheet" & Sheets("Source").Index & "$] to use "Source" as the sheet in place of "Sheet2".
I have to use LEFT JOIN because I am getting error with only JOIN and later deleted the extra rows from Sheet3 for the records not matching in Sheet1, also you may have to use UNION function since FULL JOIN is not supported in case if you want data from both the table.
Hope this helps for someone...
Option Explicit
Sub JoinTables()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & ThisWorkbook.Name & ";" & _
"Extended Properties=Excel 8.0;"
.Open
End With
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "SELECT * FROM [Sheet2$] LEFT JOIN [Sheet1$] ON [Sheet2$].[Emp_id] = [Sheet1$].[Emp_id]", cn
With Worksheets("Sheet3")
.Cells(2, 1).CopyFromRecordset rs
End With
rs.Close
cn.Close
End Sub
Upvotes: 1