|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
beleqing 发表于 2013-12-30 09:27
谢谢大版主
这个程序涉及知识比较多,没有基础是看不懂的,建议学习一个VBA知识- Sub 宏1()
- Dim cnn As Object, SQL$, Mypath$, MyFile$, m&, n&, t$
- Dim Fso As Object, arrf$(), mf&, sFileType$, j&
- Application.ScreenUpdating = False
- sFileType = "*.xlsx"
- Set Fso = CreateObject("Scripting.FileSystemObject")
- Call GetFiles(ThisWorkbook.Path, sFileType, Fso, arrf, mf)
- ActiveSheet.UsedRange.Offset(1).ClearContents
- Set cnn = CreateObject("ADODB.Connection")
- cnn.Open "Provider=Microsoft.Ace.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" & arrf(1) '连接第一个文件
-
- For j = 1 To mf '逐个文件
- m = m + 1
- If m > 49 Then '49个工作表复制一次数据
- Range("a" & Rows.Count).End(xlUp).Offset(1).CopyFromRecordset cnn.Execute(SQL) '复制数据
- m = 1
- SQL = ""
- End If
- If Len(SQL) Then SQL = SQL & " union all "
- SQL = SQL & "select * from [Excel 12.0;Database=" & arrf(j) & "].[Sheet1$]" '联合查询语句
- Next
- If Len(SQL) Then Range("a" & Rows.Count).End(xlUp).Offset(1).CopyFromRecordset cnn.Execute(SQL) '最后再检查一个是否还有数据
- cnn.Close
- Set cnn = Nothing
- Set Fso = Nothing
- Application.ScreenUpdating = True
- End Sub
- Private Sub GetFiles(ByVal sPath$, ByVal sFileType$, ByRef Fso As Object, ByRef arrf$(), ByRef mf&) '搜索所有子文件夹中所有文件子程序
- Dim Folder As Object
- Dim SubFolder As Object
- Dim File As Object
- Set Folder = Fso.GetFolder(sPath)
- If sPath <> ThisWorkbook.Path Then
- For Each File In Folder.Files
- If File.Name Like sFileType Then
- mf = mf + 1
- ReDim Preserve arrf(1 To mf)
- arrf(mf) = sPath & "" & File.Name
- End If
- Next
- End If
- If Folder.SubFolders.Count > 0 Then
- For Each SubFolder In Folder.SubFolders
- Call GetFiles(SubFolder.Path, sFileType, Fso, arrf, mf)
- Next
- End If
- Set Folder = Nothing
- Set File = Nothing
- Set SubFolder = Nothing
- End Sub
复制代码 |
|