Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2013-12-02
10
Medium Priority
?
6,770 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:Murray Brown
[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
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!

 
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:Murray Brown
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 2000 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 2000 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:Murray Brown
ID: 39698448
Thanks for the help
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Freeze panes is an option within all variants of Excel to enable parts of a sheet to remain stationary when the cursor is in another part of the sheet. This is a very useful feature which is overlooked or under used.
How to get Spreadsheet Compare 2016 working with the 64 bit version of Office 2016
This Micro Tutorial will demonstrate on a Mac how to change the sort order for chart legend values and decrpyt the intimidating chart menu.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

609 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