|
- Sub test1() '根据提供的工作表一次性汇总,有就汇总。另外,此法要求工作簿不超过49个,同名工作表格式一致。 若超49个工作簿得另写。
- Dim Conn As Object, rs As Object, Cata As Object, tb As Object, Dict As Object
- Dim p As String, f As String, strConn As String, s As String, t As String
- Dim j As Long, k, Sht As Worksheet
-
- Set Dict = CreateObject("Scripting.Dictionary")
- Application.ScreenUpdating = False
- For Each Sht In Worksheets
- With Sht
- .Cells.Clear 'Contents
- Dict.Add .Name & "$", vbNullString
- End With
- Next
- s = "Excel 12.0;HDR=yes;Database="
- If Application.Version < 12 Then
- s = Replace(s, "12.0", "8.0")
- strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=yes';Data Source="
- Else
- strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=yes';Data Source="
- End If
- Set Cata = CreateObject("ADOX.Catalog")
- p = ThisWorkbook.Path & "\"
- f = Dir(p & "*.xls*")
- Do
- If f <> ThisWorkbook.Name Then
- Cata.ActiveConnection = strConn & p & f
- For Each tb In Cata.Tables
- If tb.Type = "TABLE" Then
- t = Replace(tb.Name, "'", "")
- If Right(t, 1) = "$" Then
- If Dict.Exists(t) Then Dict(t) = Dict(t) & " UNION ALL SELECT * FROM [" & s & p & f & "].[" & t & "] WHERE 区域 IS NOT NULL"
- End If
- End If
- Next
- 'Cata.ActiveConnection = Nothing
- End If
- f = Dir
- Loop While f <> ""
- Set tb = Nothing
- Set Cata = Nothing
-
- Set Conn = CreateObject("ADODB.Connection")
- Set rs = CreateObject("ADODB.Recordset")
- Conn.Open strConn & ThisWorkbook.FullName
- For Each k In Dict.Keys
- rs.Open Mid(Dict(k), 12), Conn, 1, 3
- With Worksheets(Replace(k, "$", ""))
- For j = 0 To rs.Fields.Count - 1
- .Range("A1").Offset(0, j) = rs.Fields(j).Name
- Next
- .Range("A" & .Rows.Count).End(xlUp).Offset(1).CopyFromRecordset rs
- End With
- If rs.State = 1 Then rs.Close
- Next
- Set rs = Nothing
- Conn.Close
- Set Conn = Nothing
- Set Dict = Nothing
- Application.ScreenUpdating = True
- Beep
- End Sub
复制代码 |
|