|
数量合计给你做了,出现部门不会做
- Sub Test4()
- Dim Conn As Object, Rst As Object
- Dim strConn As String, strSQL As String, str$
- Dim i As Integer, PathStr As String
- Set Conn = CreateObject("ADODB.Connection")
- Set Rst = CreateObject("ADODB.Recordset")
- PathStr = ThisWorkbook.FullName '设置工作簿的完整路径和名称
- Select Case Application.Version * 1 '设置连接字符串,根据版本创建连接
- Case Is <= 11
- strConn = "Provider=Microsoft.Jet.Oledb.4.0;Extended Properties=excel 8.0;Data source=" & PathStr
- Case Is >= 12
- strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathStr & ";Extended Properties=""Excel 12.0;HDR=YES"";"""
- End Select
-
- For Each st In ThisWorkbook.Sheets
- If st.Name <> "Sheet1" Then
- str = str & " union all select [材料名称(cInvName)],sum([数量(iQuantity)]) as [数量(iQuantity)] from [" & st.Name & "$] group by [材料名称(cInvName)]"
- n = n + 1
- End If
- Next
- str = Right(str, Len(str) - 10)
- '设置SQL查询语句
- Conn.Open strConn '打开数据库链接
- strSQL = "select top 5 [材料名称(cInvName)],count(1) as 出现的表数,sum([数量(iQuantity)]) as 数量合计 from (" & str & ") group by [材料名称(cInvName)] order by count(1) desc"
- Set Rst = Conn.Execute(strSQL) '执行查询,并将结果输出到记录集对象
- With Sheet1.Range("a:c")
- .Cells.Clear
- For i = 0 To Rst.Fields.Count - 1 '填写标题
- .Cells(1, i + 1) = Rst.Fields(i).Name
- Next i
- .Range("A2").CopyFromRecordset Rst
- .Cells.EntireColumn.AutoFit '自动调整列宽
- .Cells.EntireColumn.AutoFit '自动调整列宽
- End With
- Rst.Close '关闭数据库连接
- Conn.Close
- Set Conn = Nothing
- Set Rst = Nothing
- End Sub
复制代码 |
|