Solved

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

Posted on 2013-12-02
10
5,435 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Improved? Move/Copy Add-in Replacement - How to avoid the annoying, “A formula or sheet you want to move or copy contains the name XXX, which already exists on the destination worksheet.” David Miller (dlmille)  It was one of those days… I wa…
This code takes an Excel list of URL’s and adds a header titled “URL List”. It then searches through all URL’s in column “A”, looking for duplicates. When a duplicate is found, it is moved to the top of the list. The duplicate URL’s are then highlig…
This Micro Tutorial will demonstrate on a Mac how to change the sort order for chart legend values and decrpyt the intimidating chart menu.
This Micro Tutorial will demonstrate in Google Sheets how to use the HYPERLINK function to create live links inside your spreadsheet.

932 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

17 Experts available now in Live!

Get 1:1 Help Now