如果您使用Excel for Windows,則可以通過ADO ODBC訪問Jet/ACE SQL引擎並運行SQL查詢以實現需求。是的,你可以查詢當前工作簿(上次保存的實例):
Sub RunSQL()
Dim conn As Object, rst As Object
Dim strConnection As String, strSQL As String
Dim i As Integer, fld As Object
Dim WS As Worksheet, var As Variant
Set conn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
' STRING CONNECTION (TWO VERSIONS)
' strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _
' & "DBQ=C:\Path\To\Workbook.xlsm;"
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source='C:\Path\To\Workbook.xlsm';" _
& "Extended Properties=""Excel 8.0;HDR=YES;"";"
' OPEN DB CONNECTION
conn.Open strConnection
For Each var In Array("X", "Y", "Z")
' CREATE WORKSHEET
Set WS = ActiveWorkbook.Sheets.Add(After:=Worksheets(Worksheets.Count))
WS.Name = var
' SQL STATEMENT
strSQL = " SELECT [Sheet1$].[Column A], [Sheet1$].[Column B]," _
& " [Sheet1$].[Column C]" _
& " FROM [Sheet1$]" _
& " WHERE [Sheet1$].[Column A] = '" & var & "';"
' OPEN RECORDSET
rst.Open strSQL, conn
' COLUMN HEADERS
WS.Range("A1").Activate
For i = 1 To rst.Fields.Count
WS.Cells(1, i) = rst.Fields(i - 1).Name
Next i
' DATA ROWS
WS.Range("A2").CopyFromRecordset rst
rst.Close
Next var
conn.Close
Set rst = Nothing: Set conn = Nothing
End Sub
這工作幾乎完美!唯一的是第一行,「X,貓,藍色」也是Y和Z頁中的第一行。你知道什麼可能導致這個問題? – Abtra16
感謝您的幫助到目前爲止@ user3598756 – Abtra16
我假設數據有第一行作爲標題行。如果你沒有它,只需添加它並重新運行!讓我知道 – user3598756