马上注册,结交更多财务经理人,享用更多功能,成就财务总监之路……
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
单击一下按钮,轻松汇总文件夹内所有Excel文件(*.xls)的所有工作表记录。 Code: Private Sub CommandButton1_Click() Dim d As New Dictionary, arr(), i%, j% Dim cn As New ADODB.Connection Dim rst As New ADODB.Recordset Dim cat As New Catalog Dim sql$, MyPath$, MyFiles$, TWb$
On Error GoTo Err Cells = Empty '清空单元格数据 TWb = ThisWorkbook.Name
MyPath = ThisWorkbook.Path MyFiles = Dir(MyPath & "*.xls") Do While MyFiles <> "" If TWb <> MyFiles Then d.Add MyFiles, 0 j = j + 1 End If MyFiles = Dir Loop
If j = 0 Then MsgBox "没有文件可合并", , "gvntw" Exit Sub End If
arr = d.Keys: d.RemoveAll For i = 0 To UBound(arr) cn.Open "Provider=Microsoft.Jet.OleDb.4.0;Extended Properties=Excel 8.0;Data Source=" & MyPath & "" & arr(i) Set cat.ActiveConnection = cn For Each Tabs In cat.Tables sql = "Select """ & Replace(arr(i), ".xls", "") & """ as 单位,""" & Replace(Tabs.Name, "$", "") & """ as 月份,* From [Excel 8.0;DATABASE=" & MyPath & "" & arr(i) & "].[" & Tabs.Name & "]" d.Add sql, 0 Next cn.Close Next sql = Join(d.Keys, " UNION ALL ") sql = "SELECT * from (" & sql & ") order by 姓名,月份" cn.Open "Provider=Microsoft.Jet.OleDb.4.0;Extended Properties=Excel 8.0;Data Source=" & arr(0) Set rst = cn.Execute(sql) For i = 1 To rst.Fields.Count Cells(1, i) = rst(i - 1).Name Next
Range("a2").CopyFromRecordset rst rst.Close: Set rst = Nothing cn.Close: Set cn = Nothing: Set d = Nothing MsgBox "表格已汇总完成", , "gvntw" Exit Sub Err: MsgBox Err.Description, , "错误报告" End Sub 2008-8/20088131174698803.zip
|