- Sub test()
- Dim Cn As Object, Rs As Object, Dict As Object, Sq As String
- Dim ar, j As Long, r As Long, c As Long, x As Long, y As Long
- Set Dict = CreateObject("Scripting.Dictionary")
- Set Cn = CreateObject("ADODB.Connection")
- Set Rs = CreateObject("ADODB.Recordset")
- Cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.Path & "\示例.accdb"
- Sq = "SELECT 简称,号码 FROM 示例"
- Rs.Open Sq, Cn, 1, 3
- ar = Rs.GetRows()
- ReDim br(1 To UBound(ar, 2) + 1, 1 To UBound(ar, 2) + 1) As String
- c = 1: br(1, 1) = "简称": br(2, 1) = "号码"
- For j = 0 To UBound(ar, 2)
- If Not Dict.Exists(ar(0, j)) Then
- c = c + 1
- br(1, c) = ar(0, j)
- br(2, c) = ar(1, j)
- Dict(ar(0, j)) = Array(3, c)
- Else
- y = Dict(ar(0, j))(0)
- x = Dict(ar(0, j))(1)
- br(y, x) = ar(1, j)
- Dict(ar(0, j)) = Array(y + 1, x)
- If y > r Then r = y: br(y, 1) = "号码"
- End If
- Next
- Range("A1").Resize(r, c) = br
- Rs.Close: Cn.Close: Set Rs = Nothing: Set Cn = Nothing: Set Dict = Nothing: Beep
- End Sub
复制代码 |