|
请教下我想用VBA SQL查询除了查询表之外的所有的工作表,这个VBA代码要怎么修改?
Sub SQL多表查询()
On Error Resume Next
Application.ScreenUpdating = False
With Sheets("数据查询")
Dim Cn As Object, Sq$(2)
.Range("c4:l" & .Cells(Rows.Count, 2).End(xlDown).Row).ClearContents
Set Cn = CreateObject("ADODB.Connection")
Cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=no';Data Source=" & ThisWorkbook.FullName
Sq(0) = "[" & "数据查询" & "$a4:b" & Cells(Rows.Count, 2).End(xlUp).Row & "]a"
Sq(1) = "[Excel 12.0;HDR=no;Database=" & ThisWorkbook.FullName & "].[初一各科成绩$A3:l]b"
Sq(2) = "SELECT b.f3,b.f4,b.f5,b.f6,b.f7,b.f8,b.f9,b.f10,b.f11 FROM " & Sq(0) & " LEFT JOIN " & Sq(1) & " ON a.f2=b.f2 "
Range("c4").CopyFromRecordset Cn.Execute(Sq(2))
Cn.Close: Set Cn = Nothing
For k = 4 To .Cells(Rows.Count, 2).End(xlDown).Row
n = n + 1
If .Cells(k, 2) <> "" Then .Cells(k, 1) = n
Next
Sheets("数据查询").Activate
End With
Application.ScreenUpdating = True
End Sub
|
|