Solved

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

Posted on 2013-12-02
10
5,637 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
ID: 39689363
What happens if the data is different for the two IDs?
0
 
LVL 4

Expert Comment

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

Expert Comment

by:Rory Archibald
ID: 39689519
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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 7

Expert Comment

by:printnix63
ID: 39689585
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
ID: 39689665
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
 
LVL 43

Expert Comment

by:Saqib Husain, Syed
ID: 39689676
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
ID: 39689682
Yes, agreed!
0
 
LVL 16

Assisted Solution

by:Jerry Paladino
Jerry Paladino earned 500 total points
ID: 39692096
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
ID: 39695895
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
ID: 39698448
Thanks for the help
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INDEX and MATCH can be used to great effect to replace HLOOKUP and VLOOKUP as it does not have the limitation of needing the data to be sorted so that the reference value is in the first column or row. It also has the ability to perform a bi-directi…
Convert between Excel file formats (.XLS, .XLSX, .XLSM) with/without macro option David Miller (dlmille) Intro Over this past Fall, I've had the opportunity to see several similar requests and have developed a couple related solutions associate…
The viewer will learn how to create two correlated normally distributed random variables in Excel, use a normal distribution to simulate the return on different levels of investment in each of the two funds over a period of ten years, and, create a …
This Micro Tutorial will demonstrate on a Mac how to change the sort order for chart legend values and decrpyt the intimidating chart menu.

803 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