Solved

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

Posted on 2013-12-02
10
6,162 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

How to get Spreadsheet Compare 2016 working with the 64 bit version of Office 2016
This article describes a serious pitfall that can happen when deleting shapes using VBA.
The viewer will learn how to use a discrete random variable to simulate the return on an investment over a period of years, create a Monte Carlo simulation using the discrete random variable, and create a graph to represent the possible returns over…
This Micro Tutorial demonstrates in Microsoft Excel how to consolidate your marketing data by creating an interactive charts using form controls. This creates cool drop-downs for viewers of your chart to choose from.

729 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