VBA合并列

时间:2018-09-24 21:19:40

标签: vba excel-vba

如何使用VBA合并2个表,使其看起来像下面的样子?

表1:

Name          Sales
John Smith    200
John Smith    50
Charles Doe   10

表2:

Name          Behavior
John Smith    Website
John Smith    Store
Charles Doe   Store

组合表:

Name            Sales   Behavior
John Smith      200     Website
John Smith      200     Store
John Smith      50      Website
John Smith      50      Store
Charles Doe     10      Store

1 个答案:

答案 0 :(得分:0)

VBA中用于将Excel工作表,范围或表作为数据集处理的SQL查询是解决您的问题的理想解决方案。实际上,对于大型数据集,VBA中的SQL查询比其他内置Excel VBA方法要快。

下面,我将提供有关您的问题的样板代码,它将帮助您了解Excel中内置的SQL查询,如何使用它们,然后您可以在Internet上搜索遇到的特定问题。

Sub RunSELECT()
    Dim cn As Object, rs As Object, output As String, sql as String

    '---Connecting to the Data Source---
    Set cn = CreateObject("ADODB.Connection")
    With cn
        .Provider = "Microsoft.ACE.OLEDB.12.0"
        .ConnectionString = "Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & _
        "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
        .Open
    End With


    '---Run the SQL SELECT Query---
    sql =  " SELECT T1.[Name], T1.[Sales], T2.[Behaviour] " & _
         " FROM " & GetRangeAddressfromTableName(Sheet1, "Table1") & " T1  " & _
         "CROSS JOIN " & GetRangeAddressfromTableName(Sheet2, "Table2") & " T2 " & _
         " ORDER BY T1.[Sales] DESC, T1.[Name] "
    Set rs = cn.Execute(sql)

    'Paste the result after SQL execution
    Sheet3.Range("A1").CopyFromRecordset rs

    '---Clean up---
    rs.Close
    cn.Close
    Set cn = Nothing
    Set rs = Nothing
End Sub

Function GetRangeAddressfromTableName(ByRef wks As Worksheet, ByVal tblName As String) As String
    GetRangeAddressfromTableName = "[" & wks.Name & "$" & wks.ListObjects(tblName).Range.Address(0, 0) & "]"
End Function