加入两个excel表

时间:2014-09-11 21:18:07

标签: sql excel

我有两个excel表结构和顺序

结构包含

Product | Component | Order_Quantity
A       | C1        | 1 
A       | C2        | 3 
A       | C3        | 3 
B       | C1        | 1 
B       | C4        | 2 
C       | C1        | 1 
D       | C2        | 3 
C       | C3        | 3 

订单包含

Order_n | Product | Quantity
1       | A       | 10
2       | B       | 10
3       | A       | 10
4       | C       | 10
6       | B       | 10

我如何加入excel 2013中的两个表(没有电源支点或其他加载项)来查看这样的结果:

Order_n | Product | Order_Qty | component | Quantity | Total_QTY
1       | A       | 10        | C1        | 1        | 10
1       | A       | 10        | C2        | 3        | 30
1       | A       | 10        | C3        | 3        | 30
2       | B       | 10        | C1        | 1        | 10
2       | B       | 10        | C4        | 2        | 20
3       | A       | 10        | C1        | 1        | 10
3       | A       | 10        | C2        | 3        | 30
3       | A       | 10        | C3        | 3        | 30
4       | C       | 10        | C1        | 1        | 10
4       | C       | 10        | C3        | 3        | 30
6       | B       | 10        | C1        | 1        | 10
6       | B       | 10        | C4        | 2        | 20

1 个答案:

答案 0 :(得分:1)

您必须使用VBA。 这应该有效......无法测试整个事情,所以让我知道它是否有效。

Sub JoinTables()

    Dim cn
    Dim rs
    Dim strFile As String
    Dim strCon As String
    Dim strSQL As String
    Dim strTbl1 As String
    Dim strTbl2 As String
    Dim JoinField As String
    Dim Table1Name As String
    Dim Table2Name As String
    Dim Table3Address As String
    Dim Table1Worksheet As String
    Dim Table2Worksheet As String
    Dim Table3Worksheet As String



    ' CHANGE THESE!
    Table1Name = "structure": Table1Worksheet = "Sheet1"  ' Name of table and name of the worksheet it is on
    Table2Name = "order": Table2Worksheet = "Sheet1"
    Table3Address = "A2": Table3Worksheet = "Sheet2"  ' The result
    JoinField = "Product"
    ' ==================================

    strFile = ThisWorkbook.FullName
    strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"

    Set cn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")

    cn.Open strCon

    strTbl1 = " [" & Table1Worksheet & "$" & Replace(ThisWorkbook.Worksheets(Table1Worksheet).ListObjects(Table1Name).Range.AddressLocal, "$", "") & "] AS T1 "
    strTbl2 = " [" & Table2Worksheet & "$" & Replace(ThisWorkbook.Worksheets(Table2Worksheet).ListObjects(Table2Name).Range.AddressLocal, "$", "") & "] AS T2 "
    strSQL = "SELECT * FROM " & strTbl1 & " LEFT JOIN " & strTbl2 & " ON T1." & JoinField & "=T2." & JoinField

    rs.Open strSQL, cn

    ThisWorkbook.Worksheets(Table3Worksheet).Range(Table3Address).CopyFromRecordset rs

    rs.Close
    cn.Close

End Sub