|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
- Sub test2() '给你写个,仅供你参考
-
- Dim dict(1) As New Dictionary
- Dim Conn As New ADODB.Connection
- Dim rs As New ADODB.Recordset
-
- Dim ar, br, i As Integer
- Dim strSQL(1) As String, strConn As String, strField As String
- Dim s As String, p As String, f As String
- 'Const adStateOpen As Long = 1
- 'Const adOpenKeyset As Long = 1
- 'Const adLockOptimistic As Long = 3
-
- Rows("2:" & Rows.Count).ClearContents
- Application.ScreenUpdating = False
-
- 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
- Conn.Open strConn & ThisWorkbook.FullName
-
- p = ThisWorkbook.Path & "\数据文件夹\"
- f = Dir(p & "*.xls*")
- Do
- If p & f <> ThisWorkbook.FullName Then
- strSQL(0) = "SELECT * FROM [" & s & p & f & "].[$A1:Z1] WHERE FALSE"
- Set rs = Conn.Execute(strSQL(0))
- For i = 0 To rs.Fields.Count - 1
- strField = rs.Fields(i).Name
- If Not strField Like "F[1-9]*" Then
- strField = "`" & strField & "`"
- If Not dict(0).Exists(strField) Then dict(0).Add strField, dict(0).Count
- End If
- Next
- End If
- f = Dir
- Loop While f <> ""
-
- br = dict(0).Keys
- For i = LBound(br) To UBound(br)
- br(i) = "NULL AS " & br(i)
- Next
-
- f = Dir(p & "*.xls*")
- Do
- If p & f <> ThisWorkbook.FullName Then
- strSQL(0) = "SELECT * FROM [" & s & p & f & "].[$A1:Z1] WHERE FALSE"
- strSQL(1) = "SELECT [.Fields] FROM [" & s & p & f & "].[$A1:Z]"
- ar = br
- Set rs = Conn.Execute(strSQL(0))
- For i = 0 To rs.Fields.Count - 1
- strField = "`" & rs.Fields(i).Name & "`"
- If dict(0).Exists(strField) Then ar(dict(0)(strField)) = strField
- Next
- dict(1).Add Replace(strSQL(1), "[.Fields]", Join(ar, ",")), ""
- End If
- f = Dir
- Loop While f <> ""
-
- If rs.State = adStateOpen Then rs.Close
- rs.Open Join(dict(1).Keys, " UNION ALL "), Conn, adOpenKeyset, adLockOptimistic
-
- With Range("A3")
- For i = 0 To rs.Fields.Count - 1
- .Offset(0, i) = rs.Fields(i).Name
- Next
- .Offset(1).CopyFromRecordset rs
- ' With .CurrentRegion
- ' .Font.Name = "微软雅黑"
- ' .Font.Size = 11
- ' .Rows(1).Font.Bold = True
- ' .HorizontalAlignment = xlCenter
- ' .Borders.LineStyle = xlContinuous
- ' End With
- End With
-
- If rs.State = adStateOpen Then rs.Close
- Set rs = Nothing
- If Conn.State = adStateOpen Then Conn.Close
- Set Conn = Nothing
- For i = 0 To UBound(dict)
- Set dict(i) = Nothing
- Next
-
- Application.ScreenUpdating = True
- Beep
- End Sub
复制代码 |
评分
-
1
查看全部评分
-
|