|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
- Sub test()
- Dim sql$, arr
- sql = "select 物料号, 零件名, 供应商, sum(单台数量) from [清单$k2:ah] group by 物料号, 零件名, 供应商"
- arr = GET_SQL(sql, False)
- Sheets("汇总").[b3].Resize(UBound(arr) + 1, UBound(arr, 2) + 1) = arr
- End Sub
- Public Function GET_SQL(strSQL As String, Optional HasHeader As Boolean = True) As Variant()
- Dim Cn, Rs, arr(), i&, j&
- Set Cn = CreateObject("ADODB.Connection")
- Set Rs = CreateObject("ADODB.Recordset")
- If Application.Version < 12 Then
- Cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & ThisWorkbook.FullName
- Else
- Cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" & ThisWorkbook.FullName
- End If
- Rs.Open strSQL, Cn, 1, 3
- If HasHeader = True Then
- ReDim arr(0 To Rs.RecordCount, 0 To Rs.Fields.Count - 1)
- For i = 0 To Rs.Fields.Count - 1
- arr(0, i) = Rs.Fields(i).Name
- Next
- For i = 0 To Rs.RecordCount - 1
- For j = 0 To Rs.Fields.Count - 1
- arr(i + 1, j) = Rs.Fields(j).Value
- Next
- Rs.MoveNext
- Next
- Else
- ReDim arr(0 To Rs.RecordCount - 1, 0 To Rs.Fields.Count - 1)
- For i = 0 To Rs.RecordCount - 1
- For j = 0 To Rs.Fields.Count - 1
- arr(i, j) = Rs.Fields(j).Value
- Next
- Rs.MoveNext
- Next
- '注意用GetRows方法转置会遇到NULL转置报错的情况
- End If
- GET_SQL = arr
- Cn.Close
- Set Rs = Nothing
- Set Cn = Nothing
- End Function
复制代码 |
|