msado15.dll を取得するには、MDAC をインストールする必要がありました。取得したら、(Win7 64 ビットで) 参照を追加しました。
C:\Program Files (x86)\Common Files\System\ado\msado15.dll
次に、現在アクティブなワークブックに存在するシート名を渡すことで、ADODB.Recordset オブジェクトを返す関数を作成しました。Test() Sub を含めて、動作するかどうかを確認する必要がある場合は、他のコードを次に示します。
Public Function RecordSetFromSheet(sheetName As String)
Dim rst As New ADODB.Recordset
Dim cnx As New ADODB.Connection
Dim cmd As New ADODB.Command
'setup the connection
'[HDR=Yes] means the Field names are in the first row
With cnx
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source='" & ThisWorkbook.FullName & "'; " & "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"
.Open
End With
'setup the command
Set cmd.ActiveConnection = cnx
cmd.CommandType = adCmdText
cmd.CommandText = "SELECT * FROM [" & sheetName & "$]"
rst.CursorLocation = adUseClient
rst.CursorType = adOpenDynamic
rst.LockType = adLockOptimistic
'open the connection
rst.Open cmd
'disconnect the recordset
Set rst.ActiveConnection = Nothing
'cleanup
If CBool(cmd.State And adStateOpen) = True Then
Set cmd = Nothing
End If
If CBool(cnx.State And adStateOpen) = True Then cnx.Close
Set cnx = Nothing
'"return" the recordset object
Set RecordSetFromSheet = rst
End Function
Public Sub Test()
Dim rstData As ADODB.Recordset
Set rstData = RecordSetFromSheet("Sheet1")
Sheets("Sheet2").Range("A1").CopyFromRecordset rstData
End Sub
Sheet1 データ: Field1 Field2 Field3 Red A 1 Blue B 2 Green C 3
Sheet2 にコピーするもの: 赤 A 1 青 B 2 緑 C 3
これにより、変更を加えてテストするたびに SQL に対してクエリを実行する時間を大幅に節約できます...
-- ロバート