|
请测试》》
- Sub ado() 'by feiren228
- Application.ScreenUpdating = False
- Dim fr$(), m%, p$, i&, j%, r&
- Dim cnn As Object, rs As Object, sql$
- p = ThisWorkbook.Path: m = 0
- 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
- With Sheets("汇总")
- .UsedRange.Clear
- .Range("A:A").NumberFormatLocal = "@"
- For i = 1 To UBound(fr)
- sql = "select * from [Excel 8.0;imex=1;hdr=yes;Database=" & fr(i) & "].[汇总$A2:BC] "
- Set rs = cnn.Execute(sql)
- If i = 1 Then
- For j = 0 To rs.Fields.Count - 1
- .Cells(1, j + 1) = rs.Fields(j).Name
- Next j
- End If
- r = .Cells.Find("*", Cells(1, 1), xlValues, xlWhole, xlByRows, xlPrevious).Row + 1
- .Cells(r, 1).CopyFromRecordset rs
- Next
- .UsedRange.Columns.AutoFit
- End With
- rs.Close
- Set rs = Nothing
- Set cnn = Nothing
- Application.ScreenUpdating = True
- 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
复制代码 |
|