|
- Sub test1() '练习了,也就发一下。
- Dim ar, br, Conn As Object, rs As Object
- Dim strConn As String, strSQL As String, strTab As String, i As Long
- Application.ScreenUpdating = False
- Set Conn = CreateObject("ADODB.Connection")
- If Application.Version < 12 Then
- strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=YES';Data Source="
- Else
- strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=YES';Data Source="
- End If
- Conn.Open strConn & ThisWorkbook.FullName
- With Sheet2
- ar = Application.Rept(.Range("A1").CurrentRegion.Rows(1), 1)
- br = Array(ar(2), "项目", "金额")
- For i = 2 To UBound(ar) Step 2
- strTab = "[" & .Name & "$" & .Range(.Cells(1, i), .Cells(.Rows.Count, i).End(xlUp)).Resize(, 2).Address(0, 0) & "]"
- strSQL = strSQL & " UNION ALL SELECT `" & ar(i) & "` AS " & br(0) & ",`" & ar(i + 1) & "` AS " & br(2) & ",'" & ar(i + 1) & "' AS " & br(1) & " FROM " & strTab
- Next
- End With
- strSQL = "TRANSFORM SUM(" & br(2) & ") SELECT '' AS 序号," & br(0) & " FROM (" & Mid(strSQL, 12) & ") GROUP BY " & br(0) & " PIVOT " & br(1)
- Set rs = Conn.Execute(strSQL)
- With Sheet1.Range("A3")
- .CurrentRegion.ClearContents
- For i = 0 To rs.Fields.Count - 1
- .Offset(, i) = rs.Fields(i).Name
- Next
- .Offset(1).CopyFromRecordset rs
- br = .CurrentRegion.Columns(1)
- For i = 1 To UBound(br) - 1
- br(i + 1, 1) = i
- Next
- .CurrentRegion.Columns(1) = br
- End With
- rs.Close
- Set rs = Nothing
- Conn.Close
- Set Conn = Nothing
- Application.ScreenUpdating = True
- Beep
- End Sub
复制代码 |
|