View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
merjet merjet is offline
external usenet poster
 
Posts: 812
Default Run an Access Query from Excel VBA with Parameters

Here is a working example you can easily modify to suit. In the VB
Editor menu Tools | References, check Microsoft ActiveX Data Objects
x.x Object Library.

Hth,
Merjet

Sub ADOParamQuery()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim intColIndex As Integer

Set TargetRange = Sheets("Sheet1").Cells(1, 1)
' open the database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & "c:\temp
\db1.mdb" & ";"
Set cmd = New ADODB.Command

With cmd
.ActiveConnection = cn
.CommandText = "Query1"
.CommandType = adCmdStoredProc
End With
' Build The Parameter
Set prm = New ADODB.Parameter

With prm
.Name = "Name"
.Value = "Jim"
.Type = adVarChar
.Size = 50
.Direction = adParamInput
End With
' Append The Parameter
cmd.Parameters.Append prm
' Execute It
Set rs = cmd.Execute
With rs
For intColIndex = 0 To rs.Fields.Count - 1 ' the field names
TargetRange.Offset(0, intColIndex).Value =
rs.Fields(intColIndex).Name
Next intColIndex
TargetRange.Offset(1, 0).CopyFromRecordset rs ' the recordset
data
End With
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub