|
Sub limonet()
Dim Sht As Worksheet, Cn As Object, Dic As Object, StrSQL$, F, Arr As Variant, CSet As New Collection
Dim StrField$, Brr() As Variant, i%, j%
Set Dic = CreateObject("scripting.dictionary")
Set Cn = CreateObject("Adodb.Connection")
Cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" & ThisWorkbook.FullName
For Each Sht In Worksheets
Arr = Application.Transpose(Application.Transpose(Intersect(Sht.UsedRange, Sht.Rows(1)).Value))
CSet.Add Arr
i = i + 1: ReDim Preserve Brr(1 To i): Brr(i) = Sht.Name
For Each F In CSet(i)
Dic(F) = ""
Next F
Next Sht
For i = 1 To CSet.Count
If UBound(CSet(i)) = Dic.Count Then
StrField = " *"
Else
For k = 1 To Dic.Count
If UBound(Filter(CSet(i), Dic.keys()(k - 1))) <> -1 Then
StrField = StrField & "," & Dic.keys()(k - 1)
Else
StrField = StrField & "," & "null as " & Dic.keys()(k - 1)
End If
Next k
End If
StrSQL = StrSQL & " Union all Select " & Mid(StrField, 2) & " From [" & Brr(i) & "$]"
StrField = ""
Next i
Worksheets.Add(before:=Worksheets(1)).Name = "汇总"
Set Rst = Cn.Execute(Mid(StrSQL, 12))
For j = 0 To Rst.Fields.Count - 1
Cells(1, j + 1) = Rst.Fields(j).Name
Next j
Range("A2").CopyFromRecordset Rst
End Sub |
|