|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
- Sub test2() '仅供测试
- Dim ar, br, i As Long, Dic As Object, Dict As Object
- Dim Conn As Object, rs As Object, Cata As Object, tb As Object
- Dim strConn As String, s As String, p As String, f As String, t As String
-
- Cells.Clear 'Contents
- Application.ScreenUpdating = False
-
- Set Dic = CreateObject("Scripting.Dictionary")
- Set Dict = CreateObject("Scripting.Dictionary")
-
- 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 Conn = CreateObject("ADODB.Connection")
- Conn.Open strConn & ThisWorkbook.FullName
- ' Set rs = CreateObject("ADODB.Recordset")
- Set Cata = CreateObject("ADOX.Catalog")
-
- p = ThisWorkbook.Path & "\"
- f = Dir(p & "*.xls?")
- While Len(f)
- If p & f <> ThisWorkbook.FullName 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
- Set rs = Conn.Execute("SELECT * FROM [" & s & p & f & "].[" & t & "A1:IV1] WHERE FALSE")
- For i = 0 To rs.Fields.Count - 1
- If Not rs.Fields(i).Name Like "F[1-9]*" Then Dic(rs.Fields(i).Name) = vbNullString
- Next
- End If
- End If
- Next
- End If
- f = Dir
- Wend
-
- br = Dic.Keys
- Dic.RemoveAll
- For i = 0 To UBound(br)
- Range("C1").Offset(0, i) = br(i)
- Dic.Add br(i), i
- br(i) = "NULL AS " & br(i)
- Next
- Range("A1").Resize(, 2) = Split("工作簿名 工作表名")
-
- f = Dir(p & "*.xls?")
- While Len(f)
- If p & f <> ThisWorkbook.FullName 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
- ar = br
- Set rs = Conn.Execute("SELECT * FROM [" & s & p & f & "].[" & t & "A1:IV1] WHERE FALSE")
- For i = 0 To rs.Fields.Count - 1
- If Not rs.Fields(i).Name Like "F[1-9]*" Then
- If Dic.Exists(rs.Fields(i).Name) Then ar(Dic(rs.Fields(i).Name)) = rs.Fields(i).Name
- End If
- Next
- Dict.Add "SELECT '" & Split(f, ".xls")(0) & "','" & Left(t, Len(t) - 1) & "'," & Join(ar, ",") & " FROM [" & s & p & f & "].[" & t & "] WHERE LEN(客户编码)", vbNullString
- If Dict.Count = 49 Then
- Cells(Rows.Count, 1).End(xlUp).Offset(1).CopyFromRecordset Conn.Execute(Join(Dict.Keys(), " UNION ALL "))
- Dict.RemoveAll
- End If
- End If
- End If
- Next
- End If
- f = Dir
- Wend
- Set tb = Nothing
- Set Cata = Nothing
- If Dict.Count Then Cells(Rows.Count, 1).End(xlUp).Offset(1).CopyFromRecordset Conn.Execute(Join(Dict.Keys(), " UNION ALL "))
- Set rs = Nothing
- Conn.Close
- Set Conn = Nothing
- Set Dic = Nothing
- Set Dict = Nothing
-
- Application.ScreenUpdating = True
- Beep
- End Sub
复制代码 |
评分
-
1
查看全部评分
-
|