使用.GetRows()
method、それは、開始する最初のレコードを取得するレコードの数を設定することができ、かつ単一のフィールド名または順序位置、またはフィールド名または順序位置番号の配列。
次の例は、外部Excelブックからレコードセットにデータを取得し、指定されたフィールドを配列に取得し、結果配列をワークシートに貼り付ける方法を示しています。
Option Explicit
Sub Test()
Dim sConnection As String
Dim sQuery As String
Dim oConnection As Object
Dim oRecordset As Object
Dim aData()
sConnection = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"User ID=Admin;" & _
"Data Source='" & ThisWorkbook.FullName & "';" & _
"Mode=Read;" & _
"Extended Properties=""Excel 12.0 Macro;"";"
sQuery = _
"SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Src1.xlsx' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] " & _
"WHERE Country='UK';"
Set oConnection = CreateObject("ADODB.Connection")
oConnection.Open sConnection
Set oRecordset = oConnection.Execute(sQuery)
oRecordset.MoveFirst
aData = oRecordset.GetRows(, , Array("CustomerID", "ContactName"))
With ThisWorkbook.Sheets(1)
.Cells.Delete
Output2DArray .Cells(1, 1), WorksheetFunction.Transpose(aData)
.Cells.EntireColumn.AutoFit
End With
oConnection.Close
End Sub
Sub Output2DArray(oDstRng As Range, aCells As Variant)
With oDstRng
.Parent.Select
With .Resize(_
UBound(aCells, 1) - LBound(aCells, 1) + 1, _
UBound(aCells, 2) - LBound(aCells, 2) + 1)
.NumberFormat = "@"
.Value = aCells
End With
End With
End Sub
はまた、このブックとして同じフォルダにデータソースとしてCustomersを含むSrc1.xlsx
ワークブックがあります:
![src1](https://i.stack.imgur.com/rdFQX.png)
次のように結果のワークシートがあり、あなたがCustomerID
とContactName
フィールドがある見ることができますのみ:
![result](https://i.stack.imgur.com/54gAU.png)