|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
- Sub test1() '参与练习 ……
- Sheet1.Activate
- ActiveSheet.UsedRange.Offset(2).ClearContents
- Application.ScreenUpdating = False
-
- Dim strPath As String, strFile As String
- Dim ar, br, dic As Object, dict As Object, target As Range
- Dim Conn As Object, rs As Object, Cata As Object, tb As Object
- Dim strConn As String, SQL As String, Field As String
- Dim s As String, t As String, i As Long
-
- Set target = Range("A3")
- Set dict = CreateObject("Scripting.Dictionary")
- Set dic = CreateObject("Scripting.Dictionary")
- Set Cata = CreateObject("ADOX.Catalog")
- Set Conn = CreateObject("ADODB.Connection")
-
- ar = Application.Rept(Range("A1").CurrentRegion.Rows(2).Value, 1)
- For i = 1 To UBound(ar)
- Field = "`" & ar(i) & "`"
- dic.Add Field, i
- ar(i) = "'' AS " & Field
- Next
-
- s = "Excel 12.0;HDR=YES;IMEX=1;Database="
- If Application.Version < 12 Or InStr(Application.Path, "WPS") > 0 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
-
- strPath = ThisWorkbook.Path & "\"
- strFile = Dir(strPath & "*.xls*")
- While Len(strFile)
- If strPath & strFile <> ThisWorkbook.FullName Then
- If Conn.State <> 1 Then
- Conn.Open strConn & strPath & strFile
- Cata.ActiveConnection = Conn
- Else
- Cata.ActiveConnection = strConn & strPath & strFile
- End If
- For Each tb In Cata.Tables
- If tb.Type = "TABLE" Then
- t = Replace(tb.Name, "'", vbNullString)
- If Right(t, 1) = "$" Then
- SQL = "SELECT * FROM [" & s & strPath & strFile & "].[" & t & "A2:Z] WHERE FALSE"
- Set rs = Conn.Execute(SQL)
- If rs.Fields(1).Name = "单号" Then
- br = ar
- For i = 0 To rs.Fields.Count - 1
- Field = "`" & rs.Fields(i).Name & "`"
- If dic.Exists(Field) Then br(dic(Field)) = Field
- Next
- SQL = "SELECT " & Join(br, ",") & " FROM [" & s & strPath & strFile & "].[" & t & "A2:Z] WHERE LEN(单号)>0 OR LEN(品名)>0"
- dict.Add SQL, vbNullString
- If dict.Count = 49 Then
- target.CopyFromRecordset Conn.Execute(Join(dict.Keys, " UNION ALL "))
- Set target = Range("A" & Cells.Find("*", , xlValues, , xlByRows, xlPrevious).Row + 1)
- dict.RemoveAll
- End If
- End If
- End If
- End If
- Next
- End If
- strFile = Dir
- Wend
- If dict.Count Then target.CopyFromRecordset Conn.Execute(Join(dict.Keys, " UNION ALL "))
-
- Set target = Nothing
- Set Cata = Nothing
- rs.Close: Set rs = Nothing
- Conn.Close: Set Conn = Nothing
- Set dic = Nothing: Set dict = Nothing
- Application.ScreenUpdating = True
- Beep
- End Sub
复制代码 |
|