loading...
汇总文件夹内所有工作簿的所有工作表记录
By  gvntw 发表于 2008-8-13 10:51:00 

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

 
示例附件:UploadFiles/2008-8/39307.2392123.zip
 
阅读全文 | 回复(0) | 引用通告 | 编辑

发表评论:

    大名:
    密码:
    主页:
    标题:
    loading...

 
站点公告
loading...
站点日历
loading...
最新日志
loading...
最新评论
loading...
最新留言
loading...
友情链接
站点统计
loading...
日志搜索
用户登陆



 
Powered by Oblog.