Access VBA Parameter in passthrough query to SQL Server - sql-server

I have several queries in an MS Access database. Some of these use parameters. I use the following code in VBA to provide the query with these parameters:
VBA
Dim startDate As Date
Dim endDate As Date
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
If IsNull(Me.dpFrom) Or IsNull(Me.dpTo) Then
MsgBox "Please select a date!"
ElseIf (Me.dpFrom.Value > Me.dpTo.Value) Then
MsgBox "Start date is bigger than the end date!"
Else
startDate = Me.dpFrom.Value
endDate = Me.dpTo.Value
Set dbs = CurrentDb
'Get the parameter query
Set qdf = dbs.QueryDefs("60 Dec")
'Supply the parameter value
qdf.Parameters("startDate") = startDate
qdf.Parameters("endDate") = endDate
'Open a Recordset based on the parameter query
Set rst = qdf.OpenRecordset()
'Check to see if the recordset actually contains rows
If Not (rst.EOF And rst.BOF) Then
rst.MoveFirst 'Unnecessary in this case, but still a good habit
Do Until rst.EOF = True
'Save contact name into a variable
Me.tbBUDdec.Value = rst!Som
rst.MoveNext
Me.tbLEYdec.Value = rst!Som
rst.MoveNext
Me.tbMDRdec.Value = rst!Som
rst.MoveNext
Me.tbODCdec.Value = rst!Som
rst.MoveNext
Loop
Else
MsgBox "There are no records in the recordset."
End If
rst.Close 'Close the recordset
Set rst = Nothing 'Clean up
Access Query
PARAMETERS startDate DateTime, endDate DateTime;
SELECT WarehouseCode, COUNT(DeliveryPoint) AS Som
FROM [50 resultaat]
WHERE EntryDate between [startDate] and [endDate]
GROUP BY WarehouseCode;
This is working fine. However, I am now trying to use the same code to call a passthrough query to a SQL server. This query uses a different syntax to declare and set the parameters:
SQL Server query
DECLARE #InvLineEntryDateBegin AS date
DECLARE #InvLineEntryDateEnd AS date
SET #InvLineEntryDateBegin = '2017-01-01'
SET #InvLineEntryDateEnd = '2017-05-31'
Select WarehouseCode, Count(PickOrderNr) as Som
FROM ( bla bla bla ...
I can't get my VBA code to work with the different SQL syntax. I've read several options but couldn't find anything concrete. Does anyone have experience with this query structure?
In other words: How can I, in VBA, insert parameters in a stored procedure that queries on a SQL server?

Consider building a named stored procedure that resides in SQL Server and have MS Access call it passing parameters using ADO as opposed to your current DAO method since you require parameterization. Then bind results to a recordset:
SQL Server Stored Proc
CREATE PROCEDURE myStoredProc
#InvLineEntryDateBegin DATE = '2017-01-01',
#InvLineEntryDateEnd DATE = '2017-05-31'
AS
BEGIN
SET NOCOUNT ON;
SELECT WarehouseCode, Count(PickOrderNr) as Som
FROM ( bla bla bla ... ;
END
VBA
' SET REFERENCE TO Microsoft ActiveX Data Object #.# Library
Dim conn As ADODB.Connection, cmd As ADODB.Command, rst As ADODB.Recordset
Dim startDate As Date, endDate As Date
If IsNull(Me.dpFrom) Or IsNull(Me.dpTo) Then
MsgBox "Please select a date!", vbCritical, "MISSING DATE"
Exit Sub
End if
If (Me.dpFrom.Value > Me.dpTo.Value) Then
MsgBox "Start date is bigger than the end date!", vbCritical, "INCORRECT RANGE"
Exit Sub
End if
startDate = Me.dpFrom.Value: endDate = Me.dpTo.Value
' OPEN CONNECTION
Set conn = New ADODB.Connection
conn.Open "DRIVER={SQL Server};server=servername;database=databasename;UID=username;PWD=password;"
' OPEN/DEFINE COMMAND OBJECT
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = "myStoredProc"
.CommandType = adCmdStoredProc
' BIND PARAMETERS
.Parameters.Append .CreateParameter("#InvLineEntryDateBegin", adDate, adParamInput, 0, startDate)
.Parameters.Append .CreateParameter("#InvLineEntryDateEnd", adDate, adParamInput, 0, endDate)
En With
' BIND RESULTS TO RECORDSET
Set rst = cmd.Execute
...

Simply create a pass-though query in Access and save it.
Ensure that the PT query works. It will likely look like:
Exec MySpName '2017-01-01', '2017-05-31'
Again: 100% Make sure the query works when you click on it in Access. At this point you not written any VBA code.
Once you have above pass through query working, then in VBA you can do this:
Dim strStartDate As String
Dim strEndDate As String
Dim strSQL As String
strStartDate = "'" & Format(Me.dpFrom, "yyyy-mm-dd") & "'"
strEndDate = "'" & Format(Me.dpTo, "yyyy-mm-dd") & "'"
strSQL = "exec MyStoreProc " & strStartDate & "," & strEndDate
With CurrentDb.QueryDefs("QryMyPass")
.SQL = strSQL
Set rst = .OpenRecordset
End With

If I remember right, in a pass-through query, you are passing the query definition directly to the engine in which it is going to run. So, you will have to use the SQL Server syntax for your query instead of the Access VBA syntax. Give that a try.
Also, the same goes for a Stored procedure. Use the syntax like you were to execute through SSMS.
"exec sp_mysp var1 var2" and so on.

Related

Excel VBA Runtime 3704 Operation is not allowed when object is closed

I have been using this code for some time and it works. As a matter of fact it works with a basic query. It just does not work with my new Stored Procedure. I can run the stored procedure manually. in SSMS and get my results. I thought that the error was when I was not getting data back so I added the . . . If myRS1.EOF Then . . . still getting the 3704 runtime error.
Here is my Excel (2013) Code
Private Sub cmdOK_Click()
Dim myStartDate, myEndDate
Dim myInsuranceCode
Dim objAD, objUser
Dim myDisplayName, myLastRow
Dim myMessage, myStyle, myTitle, myResult
Dim mySQL As String
Dim myConn
Dim myCmd
Dim myRS1
Dim myRange, myNamedRange, myCheckRange As Range
Dim X, Y, z
Dim myPercent, myLowEnd, myHighEnd
Dim myValue1, myValue2, myValue3, myValue4, myValue5, myValue6, myValue7, myValue8
Dim myCheckValue
Dim myHeaderRow, myDataRow, myLastColumn
'SET THESE ACCORDING TO THE REPORT. THE FIRST TWO MIGHT NOT NEED ANY CHANGES
myHeaderRow = 2
myDataRow = 3
myLastColumn = 22
'SETUP DATABASE OBJECTS
Set myConn = New ADODB.Connection
Set myCmd = New ADODB.Command
Set myRS1 = New ADODB.Recordset
Application.StatusBar = True
Application.StatusBar = "Connecting to SQL Server"
'GET DATES FROM TEH FORM AND SET SQL STATEMENT
myStartDate = frmMain.txtStartDate
myEndDate = frmMain.txtEndDate
'RUN INSURANCE STORE PROCEDURE
'SEPERATE THE INSURANCE CODE WITH A |
myInsuranceCode = "S19|S22"
mySQL = "dbo.BMH_rpt_PATIENTS_INSURANCE_LISTING '" & myStartDate & "', '" & myEndDate & "', '" & myInsuranceCode & "'"
'mySQL = "SELECT * FROM dbo.BETHESDA_ADMIT_SOURCE"
'HIDE THE FORM
frmMain.Hide
'GET THE USER THAT IS SIGNED IN
Set objAD = CreateObject("ADSystemInfo")
Set objUser = GetObject("LDAP://" & objAD.UserName)
myDisplayName = objUser.DisplayName
'OPEN CONNECTIONS TO THE DATABASE
myConn.ConnectionString = "Provider=SQLOLEDB;Data Source=mySQLServer;Initial Catalog=myDatabaseName;User ID=user;Password=xxxxxxxx;Connection Timeout=300;"
myConn.Open
'SET AND EXECUTE SQL COMMAND
Set myCmd.ActiveConnection = myConn
myCmd.CommandText = mySQL
myCmd.CommandType = adCmdText
Application.StatusBar = "Running Stored Procedure " & mySQL
myCmd.CommandTimeout = 3000
'OPEN RECORDSET
Set myRS1.Source = myCmd
myRS1.Open
'CHECK TO MAKE SURE WE ARE NOT AT THE BOTTOM OF THE SHEET COULD MEAN THERE WAS NOT DATA LAST TIME.
'THIS SAME CODE WILL REPEAT FOR THE DATA TAB
'*********** DATA *************
'CHECK TO MAKE SURE THERE IS DATA
If myRS1.EOF Then <---- THIS IS THE LINE I AM GETTING THE ERROR
Cells(myDataRow, 1).Value = "No Data Qualifies"
myMessage = "No data qualifing for your request " & mySQL
myTitle = "No Data"
myStyle = vbCritical + vbOKOnly
myResult = MsgBox(myMessage, myStyle, myTitle)
Exit Sub
End If
'SELECT THE SHEET TO CLEAR OUT THE OLD data on DATA
'IF THIS IS NOT SET ON THE SEEHET IT WILL FAIL
Set myTable = Sheets("DATA").ListObjects("DATA")
If Cells(myDataRow, 1).Value <> "" Then
myTable.DataBodyRange.Rows.Delete
End If
'COPY THE DATA TO EXCEL
Application.StatusBar = "Copying the new data."
Sheets("DATA").Cells(myDataRow, 1).CopyFromRecordset myRS1
Cells(1048576, 1).Select
Selection.End(xlUp).Select
myLastRow = ActiveCell.Row
'Application.StatusBar = "Naming the new DATA range"
'ActiveWorkbook.Names.Add Name:=myNamedRange, RefersTo:=Range(Cells(myHeaderRow, 1), Cells(myLastRow, myLastColumn))
myTable.Resize Range(Cells(myHeaderRow, 1), Cells(myLastRow, myLastColumn))
End Sub
*** This is all the VBA Code now. It is failing on the myRS1.EOF line so none of the other code even runs.
As you can see I have two mySQL statements. The first one is not working, but the second one works no issue.
If I run the SP from SSMS or even take the mySQL that is generated it runs fine in SSMS.
Here is the SP
--EXAMPLE
-- dbo.BMH_rpt_PATIENTS_INSURANCE_LISTING '11/01/2020', '11/30/2020', 'S19|S22'
ALTER PROCEDURE [dbo].[BMH_rpt_PATIENTS_INSURANCE_LISTING]
#StartDate AS DATETIME,
#EndDate AS DATETIME,
#Insurance AS VARCHAR(MAX)
AS
/** GET THE INSURANCE CODES **/
SELECT VALUE
INTO #INSURANCE
FROM STRING_SPLIT(#Insurance, '|')
/** GET THE PATIENTS FOR THE LIST **/
SELECT vv.pt_id AS 'Patient Account',
vv.alt_med_rec_no AS 'MRN'
FROM smsdss.vst_v AS vv
WHERE vv.pyr_cd IN (SELECT * FROM #INSURANCE)
AND vv.start_full_date BETWEEN #StartDate AND #EndDate
AND vv.tot_bal_amt <> 0

Passing Dynamic Query Values from Excel to SQL

Here is my stored Procedure. I am calling StartDate, EndDate as parameters from Excel. I had VBA executed for command button. The problem is I have to pass StartDate and EndDate to get the info. Is there any way I can pull data for a particular day either from StartDate or EndDate? And sometimes I pull data from both parameters? Not sure how the logic works.
CREATE PROCEDURE dbo.ProductListPrice #SellStartDate as Date, #SellEndDate as Date
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT
PR.[Name] ProductName
,PS.Name SubCategory
,PC.NAME ProductCategory
,PM.Name ProductModel
,[StandardCost]
,[ListPrice]
,CAST([SellStartDate] AS DATE) SellStartDate
,CAST([SellEndDate] AS DATE) SellEndDate
FROM [AdventureWorks2014].[Production].[Product] PR
INNER JOIN [AdventureWorks2014].[Production].[ProductSubcategory] PS
ON PR.[ProductSubcategoryID]=PS.[ProductSubcategoryID]
INNER JOIN [AdventureWorks2014].[Production].[ProductCategory] PC
ON PS.ProductCategoryID=PC.ProductCategoryID
INNER JOIN [AdventureWorks2014].[Production].[ProductModel] PM
ON PR.ProductModelID=PM.ProductModelID
WHERE SellStartDate>=#SellStartDate AND SellEndDate<=#SellEndDate
ORDER BY SellStartDate,productname
END
VBA
Private Sub CommandButton1_Click()
Dim SellStartDate As Date 'Declare the SellStartDate as Date
Dim SellEndDate As Date 'Declare the SellEndDate as Date
SellStartDate = Sheets("Sheet1").Range("B3").Value 'Pass value from cell B3 to SellStartDate variable
SellEndDate = Sheets("Sheet1").Range("B4").Value 'Pass value from cell B4 to SellEndDate variable
'Pass the Parameters values to the Stored Procedure used in the Data Connection
With ActiveWorkbook.Connections("AdventureWorksConnection").OLEDBConnection
.CommandText = "EXEC dbo.ProductListPrice '" & SellStartDate & "','" & SellEndDate & "'"
ActiveWorkbook.Connections("AdventureWorksConnection").Refresh
End With
End Sub
Assuming you want the result sets from your stored procedure into excel you can use something like this in your VBA Module.
Have your dates in a couple of cells on your spreadsheet let's assume you have the in cell A1 and A2
On your click button use the following VBA : (this is what I use, you can modify this to suit)
Sub your_sub_name()
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim par As String
Dim WSP1 As Worksheet
Set con = New ADODB.Connection
Set cmd = New ADODB.Command
Set rs = New ADODB.Recordset
Application.DisplayStatusBar = True
Application.StatusBar = "Contacting SQL Server..."
' Remove any values in the cells where we want to put our Stored Procedure's results.
Dim rngRange As Range
Set rngRange = Range("A3:H299")
ActiveSheet.Range("A3:H299").ClearContents
ActiveSheet.Select
Range("A3:H299").Select
Selection.ClearContents
' Log into our SQL Server, and run the Stored Procedure
con.Open "Provider=SQLOLEDB;Data Source=your_server_name;Initial Catalog=your_database_name;Integrated Security=SSPI;Trusted_Connection=Yes;"
cmd.ActiveConnection = con
Dim prmstation As ADODB.Parameter
Dim prmDate As ADODB.Parameter
Dim prmShift As ADODB.Parameter
' Set up the parameter for our Stored Procedure
' (Parameter types can be adVarChar,adDate,adInteger)
cmd.Parameters.Append cmd.CreateParameter("SellStartDate", adDate, adParamInput, 10, Range("A1").Text)
cmd.Parameters.Append cmd.CreateParameter("SellEndDate", adDate, adParamInput, 10, Range("A2").Text)
Application.StatusBar = "Running stored procedure..."
cmd.CommandText = "ProductListPrice "
Set rs = cmd.Execute(, , adCmdStoredProc)
' Copy the results to cell B7 on the first Worksheet
Set WSP1 = ActiveSheet
WSP1.Activate
If rs.EOF = False Then WSP1.Cells(3, 1).CopyFromRecordset rs
rs.Close
Set rs = Nothing
Set cmd = Nothing
con.Close
Set con = Nothing
Application.StatusBar = "Data successfully updated for : " & Range("AS36").Text
End Sub
You also need to modify your WHERE clause like this
where
( #SellStartDate <>'' and #SellEndDate <>'' and SellStartDate>=#SellStartDate AND SellEndDate<=#SellEndDate )
or
(#SellStartDate <>'' and #SellEndDate ='' and SellStartDate>=#SellStartDate)
or
(#SellStartDate ='' and #SellEndDate <>'' and SellEndDate<=#SellEndDate )

MS Access Report Connection to Recordset

I understand the report recordset property cant be connected too.
However I want/need to do something like:
Private Sub testLoad()
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.ActiveConnection = gcn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "mysp_ProofofJobScott"
'Your parameters
cmd.Parameters("#StartJob").value = 1234
cmd.Parameters("#Cmonth").value = "February 2020"
Set Me.Recordset = cmd.Execute
End Sub
Which would work fine...if I could bind a report to a recordset.
I am already using a variation of this for all my forms, and would like to be consistent in my approach.
I got thinking is there a way to use the cmd.execute to populate a temporary table, become a source for the recordsource or some other work around?
Easy and fast is the Passthrough query, but you have to take care on passed arguments to be valid as you just concat sp name with them.
Consider change cMonth to a date, then evaluate month in sp.
Code to create PT query:
Private Sub CreatePTProofofJobScott(StartJob As Long, cMonth As String)
Const QueryDefName As String = "PTProofofJobScott"
With CurrentDb
Dim QdfExists as Boolean
Dim qdf As DAO.QueryDef
For Each qdf In .QueryDefs
If qdf.Name = QueryDefName Then
QdfExists = True
Exit For
End If
Next
If Not QdfExists Then
.CreateQueryDef(QueryDefName)
End If
With .QueryDefs(QueryDefName)
.Connect = "ODBC;DSN=yourDsnToSqlServer" 'or Conn-String https://www.connectionstrings.com/microsoft-odbc-driver-17-for-sql-server/
.SQL = "EXEC mysp_ProofofJobScott " & StartJob & ", '" & cMonth & "'"
End With
End With
End Sub
Use in Report_Open event with wanted args:
Private Sub Report_Open(Cancel As Integer)
CreatePTProofofJobScott Split(Me.OpenArgs,";")(0), Split(Me.OpenArgs,";")(1)
Me.RecordSource = "PTProofofJobScott"
End Sub
Pass args to OpenArgs on open cmd
DoCmd.OpenReport "yourReport",acViewPreview,,,,"1234;February 2020"
For future development, you should have a look at SSRS as FoggyDay noted

Excel VBA To Call SQL Stored Procedure (Date parameter - No results!)

I finally got this code working by adding Set NOCOUNT ON in my stored procedure. I'm having trouble getting results when I use dates as parameters though.
Code as below -
Sub Button1_Click()
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.RecordSet
Dim WSP1 As Worksheet
Set con = New ADODB.Connection
Set cmd = New ADODB.Command
Set rs = New ADODB.RecordSet
'''Clear extract area'''
Worksheets("Extract").UsedRange.Delete
'''Log into SQL Server'''
con.Open "Provider = SQLOLEDB;" & _
"Data Source = MySource;" & _
"Initial Catalog = MyDatabase;" & _
"User ID = MyUser;" & _
"Password = MyPassword;"
cmd.ActiveConnection = con
'''Set up parameters for stored procedure'''
'cmd.Parameters.Append cmd.CreateParameter("lot", adVarChar, adParamInput, 7, Range("C4"))
cmd.Parameters.Append cmd.CreateParameter("startDate", adDBTimeStamp, adParamInput, Range("C2"))
cmd.Parameters.Append cmd.CreateParameter("endDate", adDBTimeStamp, adParamInput, Range("C3"))
'adDBTimeStamp
cmd.CommandText = "DB.MyStoredProc"
Set rs = cmd.Execute(, , adCmdStoredProc)
Set WSP1 = Worksheets("Extract")
WSP1.Activate
If rs.EOF = False Then WSP1.Cells(1, 1).CopyFromRecordset rs
rs.Close
Set rs = Nothing
Set cmd = Nothing
con.Close
Set con = Nothing
End Sub
As I said, just using the first parameter by itself, I get results pasted into my Worksheet as expected. When I comment that line out and try to run with the two date parameters I get nothing.
The code runs without error but shows an empty worksheet. I've got a feeling this has something to do with date formatting but am unsure how to input the dates into SQL as it needs them.
Could somebody help please?
---Update---
I've tried setting my parameters like this -
Set prm = cmd.CreateParameter("startDate", adDate, adParamInput)
cmd.Parameters.Append prm
cmd.Parameters("startDate").Value = "2017-07-17"
Set prm = cmd.CreateParameter("endDate", adDate, adParamInput)
cmd.Parameters.Append prm
cmd.Parameters("endDate").Value = "2017-07-19"
But Excel VBA still appears to be sending date through in dd/mm/yyyy format!
---Update2---
As per #avb's answer I have changed my code to include the following -
Dim sql As String
sql = "exec DB.myStoredProc '__dateParameter1__', '__dateParameter2__' ;"
sql = Replace(sql, "__dateParameter1__", Format(Range("C2").Value, "yyyy-mm-dd"))
sql = Replace(sql, "__dateParameter2__", Format(Range("C3").Value, "yyyy-mm-dd"))
cmd.CommandText = sql
Set rs = cmd.Execute()
This appears to pass the date values in the correct format, but still returns an empty recordset. As before, testing the same string with the single value VarChar works fine. It's just when I use the 2 date parameters.
Working SQL query generated by SSMS when clicking 'Execute' in menu -
DECLARE #return_value int
EXEC #return_value = [DB].[myStoredProc]
#startDate = N'2017-07-20'
SELECT 'Return Value' = #return_value
GO
Working query copied from VBA (pulls single batch number)
exec DB.myStoredProc '4238176' ;
Non-working query from VBA (attempting to pull all batches after this date)
exec DB.myStoredProc '2017-07-20' ;
Replace Range("C2") in CreateParameter with
Format(Range("C2").Value, "yyyymmdd")
Date format yyyymmdd is the only one that is always recognizable to sql server, disregarding your locale.
constructing sql statement without using parameters:
Dim sql As String
sql = "exec DB.MyStoredProc '__dateParameter__' ;"
sql = Replace(sql, "__dateParameter__", Format(Range("C2").Value, "yyyymmdd"))
cmd.CommandText = sql
Set rs = cmd.Execute()
Finally it appeared stored procedure had first, optional parameter being some other value than date, so the correct answer is:
Dim sql As String
sql = "exec DB.MyStoredProc null, '__dateParameter__' ;"
sql = Replace(sql, "__dateParameter__", Format(Range("C2").Value, "yyyymmdd"))
cmd.CommandText = sql
Set rs = cmd.Execute()
Setting your datetime data columns numberformat like this.
Set WSP1 = Worksheets("Extract")
With WSP1
If rs.EOF = False Then .Cells(1, 1).CopyFromRecordset rs
.Columns("c").NumberFormat = "yyyy-mm-dd" '<~~~ datetime data column c
End With

Querying a SQL Server in Excel with a parameterized query using VBA

I'm trying to query a table in Microsoft Excel using VBA. I've written up some code to try and accomplish this task, but I keep getting a run-time error '1004' saying it's a General ODBC error. I'm not sure what I need to do to get this code to run properly so I can query this table.
I'm using SQL Server Express, the server I'm connecting to: .\SQLEXPRESS
Database:
Databaselink
Querying the products table
VBA Code:
Sub ParameterQueryExample()
'---creates a ListObject-QueryTable on Sheet1 that uses the value in
' Cell Z1 as the ProductID Parameter for an SQL Query
' Once created, the query will refresh upon changes to Z1.
Dim sSQL As String
Dim qt As QueryTable
Dim rDest As Range
'--build connection string-must use ODBC to allow parameters
Const sConnect = "ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=.\SQLEXPRESS;" & _
"Database=TSQL2012;" & _
"Trusted_Connection=yes"
'--build SQL statement
sSQL = "SELECT *" & _
" FROM TSQL2012.Production.Products Products" & _
" WHERE Products.productid = ?;"
'--create ListObject and get QueryTable
Set rDest = Sheets("Sheet1").Range("A1")
rDest.CurrentRegion.Clear 'optional- delete existing table
Set qt = rDest.Parent.ListObjects.Add(SourceType:=xlSrcExternal, _
Source:=Array(sConnect), Destination:=rDest).QueryTable
'--add Parameter to QueryTable-use Cell Z1 as parameter
With qt.Parameters.Add("ProductID", xlParamTypeVarChar)
.SetParam xlRange, Sheets("Sheet1").Range("Z1")
.RefreshOnChange = True
End With
'--populate QueryTable
With qt
.CommandText = sSQL
.CommandType = xlCmdSql
.AdjustColumnWidth = True 'add any other table properties here
.BackgroundQuery = False
.Refresh
End With
Set qt = Nothing
Set rDest = Nothing
End Sub
I found this Stack Overflow question with a Google search. It does not look like anyone has tried answering it, so here's what I ended up doing. Instead of using "QueryTable", use an ADO command object as done in this MSDN article.
MSDN Example:
Dim Conn1 As ADODB.Connection
Dim Cmd1 As ADODB.Command
Dim Param1 As ADODB.Parameter
Dim Rs1 As ADODB.Recordset
Dim i As Integer
' Trap any error/exception.
On Error Resume Next
' Create and Open Connection Object.
Set Conn1 = New ADODB.Connection
Conn1.ConnectionString = "DSN=Biblio;UID=admin;PWD=;"
Conn1.Open
' Create Command Object.
Set Cmd1 = New ADODB.Command
Cmd1.ActiveConnection = Conn1
Cmd1.CommandText = "SELECT * FROM Authors WHERE AU_ID < ?"
' Create Parameter Object.
Set Param1 = Cmd1.CreateParameter(, adInteger, adParamInput, 5)
Param1.Value = 5
Cmd1.Parameters.Append Param1
Set Param1 = Nothing
' Open Recordset Object.
Set Rs1 = Cmd1.Execute()

Resources