|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
请测试》》
- Sub ado查询() 'by feiren228
- Dim fr$(), m%, p$, i&, j&, arr, brr, k, temp, kk
- Dim cnn As Object, rs As Object, sql$
- Set d = CreateObject("scripting.dictionary")
- Set d1 = CreateObject("scripting.dictionary")
- p = ThisWorkbook.Path
- Call GetFiles(fr, m, p)
- Set cnn = CreateObject("Adodb.Connection")
- Set rs = CreateObject("adodb.recordset")
- If Application.Version * 1 <= 11 Then
- cnn.Open "Provider=Microsoft.jet.OLEDB.4.0;Extended Properties='Excel 8.0;imex=1;hdr=yes';Data Source=" & ThisWorkbook.FullName
- Else
- cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;imex=1;hdr=yes';Data Source=" & ThisWorkbook.FullName
- End If
- If m = 0 Then MsgBox "此文件夹下没有需要汇总的表格!": Exit Sub
- For i = 1 To UBound(fr)
- If i = 1 Then
- sql = "select 学号,姓名,性别,基础英语,泛读,总分,平均分 from [Excel 8.0;imex=1;Database=" & fr(i) & "].[sheet1$A3:I] where 学号 is not null"
-
- Else
- sql = sql & " union all select 学号,姓名,性别,基础英语,泛读,总分,平均分 from [Excel 8.0;imex=1;Database=" & fr(i) & "].[sheet1$A3:I] where 学号 is not null"
- End If
- Next i
- Set rs = cnn.Execute(sql)
- arr = rs.getrows
- With Sheets("汇总")
- r& = .Cells.Find("*", Cells(1, 1), xlValues, xlWhole, xlByRows, xlPrevious).Row
- brr = .Range("a1:g" & r)
- For i = 2 To UBound(brr)
- d(brr(i, 1)) = i
- Next
- For j = 1 To UBound(arr, 2)
- If d.exists(arr(0, j)) Then
- If Not d1.exists(arr(0, j)) Then
- d1(arr(0, j)) = j
- Else
- d1(arr(0, j)) = d1(arr(0, j)) & "," & j
- End If
-
- End If
- Next j
- For Each k In d1
- temp = Split(d1(k), ","): kk = UBound(temp) + 1
- If UBound(brr, 2) < kk * 4 + 3 Then ReDim Preserve brr(1 To UBound(brr), 1 To kk * 4 + 3)
- brr(d(k), 2) = arr(1, temp(0)): brr(d(k), 3) = arr(2, temp(0))
- For i = 0 To UBound(temp)
- For j = 4 To kk * 4 + 3 Step 4
- brr(d(k), j) = arr(3, temp(0)): brr(d(k), j + 1) = arr(4, temp(0))
- brr(d(k), j + 2) = arr(5, temp(0)): brr(d(k), j + 3) = arr(6, temp(0))
- Next j
- Next i
- Next
- .Range("b2:av65536,h1:av1").ClearContents
- .[a1].Resize(UBound(brr), UBound(brr, 2)) = brr
- Range("D1:G1").AutoFill Destination:=.Cells(1, 4).Resize(1, UBound(brr, 2) - 3)
- End With
- rs.Close
- Set rs = Nothing
- Set cnn = Nothing
- End Sub
- Sub GetFiles(fr$(), m%, ByVal p$)
- 'p为遍历的路径,fr为存储文件路径数组
- Dim SubFolder As Object
- Dim File As Object
- Set FSO = CreateObject("Scripting.FileSystemObject")
- Set Folder = FSO.GetFolder(p)
- For Each File In Folder.Files
- If File.Name <> ThisWorkbook.Name Then
- If File.Name Like "*.xls" Or File.Name Like "*.xlsx" Then
- m = m + 1
- ReDim Preserve fr(1 To m)
- fr(m) = File
- End If
- End If
- Next
- For Each SubFolder In Folder.SubFolders
- Call GetFiles(fr, m, SubFolder.Path)
- Next
- End Sub
复制代码 |
评分
-
1
查看全部评分
-
|