|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
Sub ADO法()
Dim cnn As Object, rs As Object, SQL$, Fso As Object, Folder As Object, i&, j&, l&, wb As Workbook, d As Object, k, t, arr
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set d = CreateObject("scripting.dictionary")
Set cnn = CreateObject("adodb.connection")
Set Fso = CreateObject("Scripting.FileSystemObject")
Set Folder = Fso.GetFolder(ThisWorkbook.Path & "\数据")
Call GetFiles(Folder, d)
Set wb = Workbooks.Add(xlWBATWorksheet)
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=excel 12.0;Data Source=" & ThisWorkbook.FullName
k = d.keys
t = d.items
For i = 0 To d.Count - 1
arr = Split(t(i), ",")
With wb.Sheets(1)
.Cells.ClearContents
For j = 0 To UBound(arr)
SQL = "select * from [Excel 12.0;Database=" & arr(i) & "].[Sheet1$]"
Set rs = cnn.Execute(SQL)
If j = 0 Then
For l = 1 To rs.Fields.Count
.Cells(1, l) = rs.Fields(l - 1).Name
Next
.[a2].CopyFromRecordset rs
Else
.Range("a" & .Rows.Count).End(xlUp).Offset(1).CopyFromRecordset cnn.Execute(SQL)
End If
Next
wb.SaveAs ThisWorkbook.Path & "\需要得到的结果\" & k(i)
End With
Next
wb.Close
Set Folder = Nothing
Set Fso = Nothing
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
Application.ScreenUpdating = True
MsgBox "ok"
End Sub
Sub GetFiles(ByVal Folder As Object, d As Object)
Dim SubFolder As Object
Dim File As Object
For Each File In Folder.Files
If File.Name Like "*.xlsx" Then
If Not d.Exists(File.Name) Then
d(File.Name) = File
Else
d(File.Name) = d(File.Name) & "," & File
End If
End If
Next
For Each SubFolder In Folder.SubFolders
Call GetFiles(SubFolder, d)
Next
End Sub
|
|