|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
SQL+字典
- Sub Test()
- Dim SH As Worksheet
- Dim lngRows As Long, intTypeNum As Integer
- Dim Conn As Object, Rst As Object, strPath As String
- Dim strConn As String, strSQL As String
- Dim rg As Range
- Dim objDic As Object
- Set SH = Sheets("Sheet1")
- lngRows = SH.Range("E" & Rows.Count).End(xlUp).Row
- If lngRows < 2 Then lngRows = 2
- Sheet1.Range("E2:F" & lngRows).ClearContents
- lngRows = SH.Range("A" & Rows.Count).End(xlUp).Row
- Set rg = SH.Range("E2")
- Set objDic = CreateObject("Scripting.Dictionary")
- Set Conn = CreateObject("ADODB.Connection")
- Set Rst = CreateObject("ADODB.Recordset")
- strPath = ThisWorkbook.FullName
- Select Case Application.Version * 1
- Case Is <= 11
- strConn = "Provider=Microsoft.Jet.Oledb.4.0;Extended Properties=excel 8.0;Data source=" & strPath
- Case Is >= 12
- strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strPath & ";Extended Properties=""Excel 12.0;HDR=YES"";"""
- End Select
- Conn.Open strConn
- '''''''''''''''''''''''''''''''''
- strSQL = "SELECT A.单据编号, A.配送方向, Count(A.配送方向) AS 计数 " & _
- "FROM (SELECT 单据编号, 配送方向 FROM [Sheet1$A1:C" & lngRows & "] GROUP BY 单据编号, 配送方向, 单位名称) AS A " & _
- "GROUP BY A.单据编号, A.配送方向 " & _
- "ORDER BY A.单据编号, Count(A.配送方向);"
- Rst.Open strSQL, Conn, 3, 1
-
- If Rst.RecordCount > 0 Then
- Rst.moveFirst
- Do Until Rst.EOF
- objDic(Rst.Fields("单据编号").Value) = Rst.Fields("配送方向").Value & "(" & Rst.Fields("计数").Value & ")"
- Rst.moveNext
- Loop
-
- rg.Resize(objDic.Count, 1) = Application.WorksheetFunction.Transpose(objDic.keys)
- rg.Offset(, 1).Resize(objDic.Count, 1) = Application.WorksheetFunction.Transpose(objDic.items)
- End If
- Set Rst = Nothing
- Set Conn = Nothing
- End Sub
复制代码 |
|