Solved

Excel VBA - Join/merge two ranges as you would with SQL

Posted on 2013-12-02
10
5,261 Views
Last Modified: 2013-12-05
Hi

I have two ranges that come from separate database tables pasted into Excel
They both have a column called ID that I want to use to merge the data as one would
do in a SQL join query. What VBA code would I use to do this?
0
Comment
Question by:murbro
  • 2
  • 2
  • 2
  • +3
10 Comments
 
LVL 43

Expert Comment

by:Saqib Husain, Syed
Comment Utility
What happens if the data is different for the two IDs?
0
 
LVL 4

Expert Comment

by:andrew_man
Comment Utility
Do you think the ODBC is suitable for your case?
0
 
LVL 85

Expert Comment

by:Rory Archibald
Comment Utility
There are various different ways. Which is best would depend on what you are doing with the data, but it would be simpler to extract the data using a query that joins the two tables in the first place if you can?
0
 
LVL 7

Expert Comment

by:printnix63
Comment Utility
If the two tables contain the same sort of data,
can't you use a Union query to combine them?

Select table1.id, table1.field from table1
Union
Select table2.id,table2.otherfield from table2

The two queries combined by Union must have the same typeset of Felds in their Field definition, but they do not need to have the same names normally.

Hope this helps
0
 

Author Comment

by:murbro
Comment Utility
Hi

This has to be done in Excel. The tables come from a SAP dump where there is a lot of security around user permissions etc
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 43

Expert Comment

by:Saqib Husain, Syed
Comment Utility
If you can give more details (preferably with a sample excel file) then probably someone can write a macro for you.
0
 
LVL 4

Expert Comment

by:andrew_man
Comment Utility
Yes, agreed!
0
 
LVL 16

Assisted Solution

by:Jerry Paladino
Jerry Paladino earned 500 total points
Comment Utility
Another option is to use Microsoft Query which is embedded in Excel.   It provides the ability to load Excel worksheets as database tables and then run SQL on those tables.

In Excel 2007-2013 - Data menu, Get External Data, From Other Sources, "From Microsoft Query".   This uses ODBC to make a connection to the Excel files.   In the "Choose Data Source" dialog, select Excel Files*.   Select the workbook in the next dialog and then select the Worksheet in the "Add Tables" dialog.   There is an "Options..." button on the "Add Tables" dialog.  Make sure "System Tables" is checked or the available worksheets in the workbook will not display.

Use the ADD button to select one or more worksheets.   From there you have the ability to join tables and write SQL.   The user interface provides some drag and drop but don't expect MS-Access like capabilities.

HTH
Jerry
0
 
LVL 16

Accepted Solution

by:
Jerry Paladino earned 500 total points
Comment Utility
For a VBA solution, the attached file has sample data and the code below.    The VBA uses ADO and a SQL query to join worksheets WS1 and WS2 on MasterID and writes the resulting recordset to the OUTPUT worksheet.

HTH
Jerry

Option Explicit

Sub SQL_On_Internal_WorkSheets()
    
    Dim oCONN As ADODB.Connection
    Dim oRS As ADODB.Recordset
    Dim wsOutput As Worksheet
    Dim strSQL As String
    Dim strConn As String
    Dim i As Long
    Dim hdrName As Variant
    
' Set the Output WorkSheet and Clear its Contents
    Set wsOutput = ActiveWorkbook.Worksheets("OUTPUT")
    wsOutput.Cells.ClearContents
    
' Establish the ADO Connection, Recordset & Connection String variables for the ActiveWorkbook
' "Microsoft.ACE.OLEDB.12.0" and "Excel 12.0" imply Excel 2007 or higher
    Set oCONN = New ADODB.Connection
    Set oRS = New ADODB.Recordset
    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                "Data Source=" & ActiveWorkbook.FullName & ";" & _
                "Extended Properties=""Excel 12.0;HDR=Yes;"";"
    
' Build the SQL statement
    strSQL = "SELECT [WS1$].* " & _
             "FROM [WS1$] INNER JOIN [WS2$] " & _
             "ON [WS1$].MasterID = [WS2$].MasterID"
    
' Open the Connection and run the SQL Statement
    oCONN.Open strConn
    oRS.Open strSQL, oCONN
    
' Write the Headers to the Output worksheet
    i = 1
    For Each hdrName In oRS.Fields
        wsOutput.Cells(1, i).Value = hdrName.Name
        i = i + 1
    Next
    
' Write the Result Set of the SQL Query to the Output Worksheet
    wsOutput.Cells(2, 1).CopyFromRecordset oRS
    
' Convert the Output data list to an Excel Table
    With wsOutput
        .Activate
        .ListObjects.Add(xlSrcRange, ActiveSheet.UsedRange, , xlYes).Name = "Tbl_Output"
        .Cells.EntireColumn.AutoFit
    End With
    
' Cleanup and close the connection
    oCONN.Close
    Set oCONN = Nothing
    Set oRS = Nothing
    
End Sub

Open in new window

Run-SQL-on-Excel-Sheets-with-ADO.xlsm
0
 

Author Closing Comment

by:murbro
Comment Utility
Thanks for the help
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Drop Down List with Unique/Distinct Values (Part II - ComboBox or ListBox and Data Validation List Bonus!) David Miller (dlmille) Intro This article focuses on delivering unique, sorted lists to list objects (e.g., ComboBox, ListBox) and Dat…
This article descibes how to create a connection between Excel and SAP and how to move data from Excel to SAP or the other way around.
The viewer will learn how to use the =DISCRINV command to create a discrete random variable, use this command to model a set of probabilities and outcomes in a Monte Carlo simulation, and learn how to find the standard deviation of a set of probabil…
This Micro Tutorial will demonstrate the scrolling table in Microsoft Excel using the INDEX function.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now