パラメータクエリを実行する
Sub パラメータクエリ1()
'変数のデータ型宣言と同時に新規オブジェクトを作成する
Dim myCon As New ADODB.Connection, myCmd As New ADODB.Command
Dim myRS As New Recordset, FileName As String
FileName = ThisWorkbook.Path & "\mdb\2-sampleDB.mdb"
myCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FileName
With myCmd
.ActiveConnection = myCon
.CommandText = "PQ_所属で抽出"
End With
'「営業1課」と言う値をパラメータクエリに渡して実行後、転記
Set myRS = myCmd.Execute(Parameters:="営業1課")
Range("A1").CopyFromRecordset myRS
Set myCmd = Nothing
myRS.Close: Set myRS = Nothing
myCon.Close: Set myCon = Nothing
End Sub
使用するパラメータクエリ
実行結果
複数のパラメータを渡す
Sub パラメータクエリ2()
'複数のパラメータ
Dim myCon As New ADODB.Connection, myCmd As New ADODB.Command
Dim myRS As New Recordset, FileName As String, myAge As Variant
FileName = ThisWorkbook.Path & "\mdb\2-sampleDB.mdb"
myCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FileName
With myCmd
.ActiveConnection = myCon
.CommandText = "PQ_年齢で抽出"
End With
'複数のパラメータを配列に格納し、パラメータクエリに引数として渡す
myAge = Array(25, 30)
Set myRS = myCmd.Execute(Parameters:=myAge)
Range("A1").CopyFromRecordset myRS
Set myCmd = Nothing
myRS.Close: Set myRS = Nothing
myCon.Close: Set myCon = Nothing
End Sub
使用するパラメータクエリ
実行結果

