Sub 合并数据()
Dim cnn As Object, rs As Object
Dim SQL$, MyFile$, s$, m&, n&, t$, i%, z$, v%
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = ThisWorkbook.Path & ""
If .Show = False Then Exit Sub
MyPath = .SelectedItems(1) & ""
End With
Dim msg As String, nsg As String, BBB As String
Application.ScreenUpdating = False
Set cnn = CreateObject("ADODB.Connection")
Set cat = CreateObject("ADOX.Catalog")
Cells.ClearContents
MyFile = Dir(MyPath & "*.xlsx")
On Error Resume Next
Do While MyFile <> ""
If MyFile <> ThisWorkbook.Name Then
n = n + 1
If n = 1 Then
'cnn.Open "Provider=Microsoft.jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & MyPath & MyFile
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & MyPath & MyFile & "';Extended Properties='Excel 12.0 Xml';"
Else
t = "[Excel 12.0;Database=" & MyPath & MyFile & "]."
End If
cat.ActiveConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & MyPath & MyFile & "';Extended Properties='Excel 12.0 Xml';" '"Provider=Microsoft.jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & MyPath & MyFile
For Each tb1 In cat.Tables
If tb1.Type = "TABLE" Then
z = ""
z = tb1.Columns(0).Name
If Left$(z, 1) <> "F" Then
s = Replace(tb1.Name, "'", "")
If Right(s, 1) = "$" Then
v = v + 1
If v = 1 Then
Set rs = cnn.Execute("[" & s & "]")
For i = 1 To rs.Fields.Count
Cells(1, i) = rs.Fields(i - 1).Name
Next
End If
m = m + 1
If m > 49 Then
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 " & t & "[" & s & "] "
End If
End If
End If
Next
End If
MyFile = Dir()
Loop
On Error GoTo 0
If Len(SQL) Then Range("a" & Rows.Count).End(xlUp).Offset(1).CopyFromRecordset cnn.Execute(SQL)
cnn.Close
Set cnn = Nothing
Set cat = Nothing
Set tb1 = Nothing
Application.ScreenUpdating = True
End Sub