View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
Bill Pfister Bill Pfister is offline
external usenet poster
 
Posts: 132
Default Passing parameter to a select query

Using VBA, you can craft your SQL statement to contain whatever parameters
you need. In the following example, I'm pointing to a local Access database,
you would only have to modify the details (driver, etc.) in the connect
string to point to Oracle or another DBMS.


Sub AccessQueryData1()
Dim strFilename As String
Dim strSQL As String
Dim strConn As String
Dim strSeparator As String

strSeparator = Chr(13) & "" & Chr(10)

strFilename = "D:\Data\Test.mdb"
strConn = "ODBC;DSN=0_ptd_test1;DBQ=" & strFilename &
";DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;"


strSQL = "SELECT Category.Name" & strSeparator & _
"FROM `" & strFilename & "`.Category Category " & strSeparator
& _
"WHERE Category.Name < 'Administrative' "


' Focus on only the parameter
With ActiveSheet.QueryTables.Add(Connection:=strConn,
Destination:=Range("C6"))
.CommandText = Array(strSQL)
End With

' All the other parameters
With ActiveSheet.QueryTables.Add(Connection:=strConn,
Destination:=Range("C6"))
.CommandText = Array(strSQL)
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=False
End With
Range("E11").Select
End Sub


"Seamus Conlon" wrote:

"Bill Pfister" wrote in message
...
How are you executing the query (SQL statement queried to a recordset in
Excel VBA, other?)?

To insert the query in the worksheet I initially used the
New Database Query option under Import External Data.
To refresh it I have a macro that uses something like:

Selection.QueryTable.Refresh

Thanks,
Seamus