|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
本帖最后由 可爱天使 于 2018-7-21 16:54 编辑
两表合并代码,但表头有很多中文表题时运行不起来
Private Sub CommandButton1_Click()
Dim i%, c%, n%
Dim SQL$, myField$
Dim Dkey
Dim Arr()
Dim Cnn As Object
Dim Rst As Object
Dim Dic1 As Object
Dim Dic2 As Object
Dim regEx As Object
Dim Sh As Worksheet
Application.ScreenUpdating = False
'确定完整的表头
Set Dic1 = CreateObject("Scripting.Dictionary")
Set Dic2 = CreateObject("Scripting.Dictionary")
For Each Sh In Sheets
If Not Sh.Name Like "*汇总表*" Then
c = Sh.Range("IV1").End(xlToLeft).Column
Arr = Sh.Range("A1").Resize(1, c).Value
For i = 1 To UBound(Arr, 2)
Dic1(Sh.Name) = Dic1(Sh.Name) & Arr(1, i)
Dic2(Arr(1, i)) = ""
Next
End If
Next
myField = Join(Dic2.Keys, ",") '完整表头,用逗号连接
'设置正则表达式基本参数
Set regEx = CreateObject("VBScript.RegExp")
With regEx
.Global = True
.IgnoreCase = False
End With
Set Cnn = CreateObject("ADODB.Connection")
Set Rst = CreateObject("ADODB.Recordset")
Cnn.Open "Provider=Microsoft.ACE.OleDB.12.0;Extended Properties='Excel 12.0;HDR=YES;IMEX=1';Data Source=" & ThisWorkbook.FullName
n = 1
Columns("J:IV").ClearContents
Range("J1").Resize(1, Dic2.Count).Value = Dic2.Keys '完整表头
For Each Dkey In Dic1.Keys
r = Sheets(Dkey).Range("A65536").End(xlUp).Row
regEx.Pattern = "[^" & Dic1(Dkey) & ",]"
SQL = regEx.Replace(myField, "''")
SQL = "SELECT " & SQL & " FROM [" & Dkey & "$" & Sheets(Dkey).UsedRange.Address(0, 0) & "]"
Rst.Open SQL, Cnn, 1, 3
Range("J1").Offset(n, 0).CopyFromRecordset Rst
n = n + Rst.RecordCount
Rst.Close
Next
Cnn.Close
Set Dic1 = Nothing
Set Dic2 = Nothing
Set regEx = Nothing
Set Rst = Nothing
Set Cnn = Nothing
Application.ScreenUpdating = True
End Sub
|
|