run time error 1004 general odbc error refresh backgroundquery false - sql-server

I have a working VBA code which runs as:
wsEnd.Select
Range("A:AQ").Delete
strSQL = "Select *
strSQL = strSQL & " FROM [XXX].[ABCCustomer] As A"
strSQL = strSQL & " Left join"
strSQL = strSQL & " (Select * "
strSQL = strSQL & " From [XXX]..[ABCCustomer]"
strSQL = strSQL & " where LineageId = '123' ) B"
strSQL = strSQL & " on a.product = b.product and a.[StartDate] = b.[StartDate]"
strSQL = strSQL & " where (a.EndDate <> b.EndDate)"
strSQL = strSQL & " and a.NewEndDate is NULL AND B.NewEndDate IS NULL"
strSQL = strSQL & " and a.Id = '456"
strSQL = strSQL & " order by b.ProductType"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array(Array( _
"ODBC;DRIVER=SQL Server;SERVER=XXX\SQL01;UID=;Trusted_Connection=Yes;APP=2007 Microsoft Office system;WSID=XXX;DATA" _
), Array("BASE=master")), Destination:=Range("$A$1")).QueryTable
.CommandText = strSQL
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_Query_from_XXX_C"
.Refresh BackgroundQuery:=False
End with
I have two other scripts starting after the End With but inside the same sub all using the same VBA just different SQL, which all work perfectly fine.
Then I have this very annoying forth, which is causing my a real headache, that goes as follows:
strSQL = "Select *
strSQL = strSQL & " FROM [XXX].[ABCCustomer] As A"
strSQL = strSQL & " Left join"
strSQL = strSQL & " (Select * "
strSQL = strSQL & " From [XXX]..[ABCCustomer]"
strSQL = strSQL & " where Id = '123' ) B"
strSQL = strSQL & " on a.product = b.product and a.[StartDate] = b.[StartDate]"
strSQL = strSQL & " where (a.EndDate = b.EndDate)"
strSQL = strSQL & " and a.NewEndDate is Not NULL AND B.NewEndDate not NULL"
strSQL = strSQL & " and a.Id = '456"
strSQL = strSQL & " order by b.Product"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array(Array( _
"ODBC;DRIVER=SQL Server;SERVER=XXX\SQL01;UID=;Trusted_Connection=Yes;APP=2007 Microsoft Office system;WSID=XXX;DATA" _
), Array("BASE=master")), Destination:=Range("$A$1")).QueryTable
.CommandText = strSQL
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_Query_from_XXX_D"
.Refresh BackgroundQuery:=False
End With
End Sub
When running the code, the first three come back fine but the forth says
run time error 1004 general odbc error
and stops the code at backgroundquery=false.
I have lifted the SQL code into SQL and it works perfectly fine there and have even tried running it on a separate excel document and that doesn't give any joy.
The VBA is copy and pasted and only the list object table name is changed i.e. from C to D
I have tried to change backgroundquery:=false to background:=refresh, this works but I get a message saying
run time error 1004 This operation cannot be done because the data is refreshing in the background.

The error went away after a computer reset. Really sorry, but thanks for all those who responded.
Thanks
Matt

This isn't an answer to the question. But it is relevant, since the reason for writing it like this was to make it easier to read.
Original Code: This does a nice job of lining up the characters to read the statement, but is redundant by defining the value of strSQL for every line item.
strSQL = "Select *
strSQL = strSQL & " FROM [XXX].[ABCCustomer] As A"
strSQL = strSQL & " Left join"
strSQL = strSQL & " (Select * "
strSQL = strSQL & " From [XXX]..[ABCCustomer]"
strSQL = strSQL & " where LineageId = '123' ) B"
strSQL = strSQL & " on a.product = b.product and a.[StartDate] = b.[StartDate]"
strSQL = strSQL & " where (a.EndDate <> b.EndDate)"
strSQL = strSQL & " and a.NewEndDate is NULL AND B.NewEndDate IS NULL"
strSQL = strSQL & " and a.Id = '456"
strSQL = strSQL & " order by b.ProductType"
Modified: Aside from the color formatting getting lost in translation. This tells anyone reading it that the variable is getting set once and eliminates redundant characters to have to scan over.
strSQL = "Select * " & _
"FROM [XXX].[ABCCustomer] As A " & _
"Left join " & _
"(Select * " & _
"From [XXX]..[ABCCustomer] " & _
"where LineageId = '123' ) B " & _
"on a.product = b.product and a.[StartDate] = b.[StartDate] " & _
"where (a.EndDate <> b.EndDate) " & _
"and a.NewEndDate is NULL AND B.NewEndDate IS NULL " & _
"and a.Id = '456 " & _
"order by b.ProductType"

Related

ADODB CreateParameter in SELECT without specifying Parameter in CommandText

Using SQL Server Express 2014 with Access 2016
Front end contains a form intended to be used to search for records in the database. The VBA code on the submit for the form builds the WHERE of the SELECT statement as one long string.
This is an abbreviated example.
Set thisDb = DBEngine.Workspaces(0).Databases(0)
Set qDef = thisDb.CreateQueryDef("tempPTQ")
qDef.Connect = "ODBC;Driver={ODBC Driver 11 for SQL Server};SERVER=" & stServer & ";DATABASE=" & stDatabase & ";Trusted_Connection=Yes;"
strFields = "field1, field2, field3"
strTable = "dbo_SomeTable"
strParam = "WHERE field1=" & txtBox1.Value & ", AND field2=" & txtBox2.Value & ", AND field3=" & txtBox3.Value
strSQL = "SELECT " & strFields & " FROM " & strTable & " WHERE " & strParam & ";"
qDef.SQL = strSQL
DoCmd.RunSQL "INSERT INTO " & strDestTbl & " SELECT * FROM tempPTQ"
Is it possible to convert this to an ADODB parameterized query with a dynamic WHERE clause, essentially a variable number of columns, each represented by a different parameter?
strSQL = "SELECT field1, field2, field3 FROM someTable"
Set dbCon = New ADODB.Connection
With dbCon
.ConnectionString = "Driver={SQL Server Native Client 11.0};SERVER=" & stServer & ";DATABASE=" & stDatabase & ";Trusted_Connection=Yes;"
.Open
End With
Set dbCmd = New ADODB.Command
With dbCmd
.ActiveConnection = dbCon
.CommandText = strSQL
If txtBox1.Value <> "" Then
.CreateParameter("param1", adChar)
.Parameters(0).Value = txtBox1.Value
End If
If txtBox2.Value <> "" Then
.CreateParameter("param2", adChar)
.Parameters(1).Value = txtBox2.Value
End If
If txtBox3.Value <> "" Then
.CreateParameter("param3", adChar)
.Parameters(2).Value = txtBox3.Value
End If
Set rst = .Execute()
rst.Close
Set rst = Nothing
End With
How can parameters be dynamically added to the WHERE clause?
Consider using a collection that holds the WHERE clause statement with ? placeholders and a dictionary of corresponding parameters:
Private Function FilterCriteria() As Collection
Dim sqlCollection As New Collection
Dim strCriteria As String
Dim params As Object
Set params = CreateObject("Scripting.Dictionary")
strCriteria = "1 = 1" ' ALWAYS TRUE CONDITION TO START WHERE CLAUSE
If txtBox1.Value <> "" Then
strCriteria = strCriteria & " AND field1 = ?"
params.Add "field1param", txtBox1.Value
End If
If txtBox2.Value <> "" Then
strCriteria = strCriteria & " AND field2 = ?"
params.Add "field2param", txtBox2.Value
End If
If txtBox3.Value <> "" Then
strCriteria = strCriteria & " AND field3 = ? "
params.Add "field3param", txtBox3.Value
End If
sqlCollection.Add strCriteria
sqlCollection.Add params
Set FilterCriteria = sqlCollection
End Function
Then in your actual database call, retrieve above function's returned collection and use in prepared statement and .CreateParameters:
Dim sqlCollection As New Collection
Set sqlCollection = FilterCriteria ' CALLING ABOVE FUNCTION (RETURNED COLLECTION)
Set dbCon = New ADODB.Connection
With dbCon
.ConnectionString = "Driver={SQL Server Native Client 11.0};SERVER=" & _
stServer & ";DATABASE=" & stDatabase & ";Trusted_Connection=Yes;"
.Open
End With
' CONCATENATE WHERE CLAUSE STRING TO SQL STATEMENT
strSQL = "SELECT field1, field2, field3 FROM someTable WHERE " & sqlCollection(1)
Set dbCmd = New ADODB.Command
With dbCmd
.ActiveConnection = dbCon
.CommandText = strSQL
' BIND PARAMETERS FROM PARAMS DICT (KEYS=NAME, VALUES=PARAM VALUE)
For Each key In sqlCollection(2).keys
cmd.Parameters.Append cmd.CreateParameter(key, adVarChar, adParamInput, 255, _
sqlCollection(2)(key))
Next key
Set rst = .Execute()
rst.Close
Set rst = Nothing
End With

Automation Error when executing SQL Server Script in Excel VBA

I am opening an SQL Server Connection in EXCEL VBA and on the objMyCmd.Execute line when it is using the SQL script I am getting this error message:
"Run-time error '-2147217900 (80040e14)') Automation error"
I have reviewed other SO posts that seem to reference an issue with the connection string itself, but I don't believe that is the issue as I am able to pull the first few variables listed when eliminating the rest of the SQL script.
I have attempted to review the SQL code to see if I am using an incorrect format, or if the language is not written properly and I am not able to determine the issue. I am hoping with some Q & A we may notice something I have missed in how this is written? Please let me know if there is additional information I can provide, below is the code up to the point of error.
Sub SQL_GetAgentChart()
Dim dtDate As Date
Dim myTable As ListObject
Dim DataServer As String
Dim Database As String
Dim constring As String
DataServer = "GLSSQLMADP2"
Database = "PERF_MGMT_BWRSRV_PROD"
constring = "Driver={SQL Server};Server=" & DataServer & "; Database=" & Database & "; Trusted_Connection=yes"
Dim AVStartDate As Date
Dim AVEndDate As Date
Dim RepID As Long
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
Set myTable = Worksheets("Witness").ListObjects("tblWitness")
AVStartDate = DateValue("Mar 01, 2016")
AVEndDate = DateValue("Mar 31, 2016")
RepID = 2040
'Open Connection'
objMyConn.ConnectionString = constring
objMyConn.Open
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = " " & _
"SELECT PERSN_XTRNL_ID_NR, SOURCE, LOGGINGTS, DD7, CUREREASON, CUREDATE, LNSTATUS " & _
"FROM TTB " & _
"WITH INCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN PERSONNEL P ON T.PERSONNELID = P.PERSONNELID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE T.PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 1 " & _
"AND DD7 > 0), OUTCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN AVAYA A ON T.UID = A.TTBUID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 0 " & _
"AND A.AVAYAGROUP IN ('15', '1A', '1B', '1C', '1D', '1E', '1F', '1G', '1H') " & _
"AND DD7 > 0) "
objMyCmd.CommandType = adCmdText
objMyCmd.Execute

Excel Import Data from SQL- Date comes in as text value

I'm importing data from oracle toad database into an Excel sheet using data connection. The table includes a Date column, but this column comes to Excel as text rather than the date.
Is there any way I can fix this issue?
Sub Show_data()
Dim con As ADODB.Connection
Dim recset As ADODB.Recordset
Dim ConnectionString As String
Dim strSQL As String
Dim iCols As Integer
Set con = New ADODB.Connection
Set recset = New ADODB.Recordset
'Check for the connectivity or connected to the xx network
On Error GoTo errHandler
ConnectionString = "Provider=xx;User ID=yy;password= appsro;Data Source=zz"
con.Open ConnectionString
'Set and Excecute SQL Command'
strSQL = "SELECT B.USER_NAME AS CREATED_BY, A.CREATION_DATE, C.USER_NAME, A.LAST_UPDATE_DATE, A.PFIZER_ITEMCODE, A.SYSTEM_ITEMCODE AS ORACLE_ITEM_CODE, " & _
"A.ITEM_DESCRIPTION, A.BATCH_NUMBER, A.MFR_CODE, A.MFR_DESC AS MFR_DESCRIPTION, TO_CHAR(A.MFR_DATE,'DD-MON-YYYY')As MFR_DATE, TO_CHAR(A.EXPIRY_DATE,'DD-MON-YYYY')As EXPIRY_DATE, " & _
"TO_CHAR(A.EFFECTIVE_FROM,'DD-MON-YYYY') AS EFFECTIVE_FROM, " & _
"A.EFFECTIVE_TO, A.EXCISE AS EXCISE_AMOUNT, A.EXCISE_RATE, A.P2S, A.P2R, A.MRP, A.STATE_CODE, A.STATE, " & _
"(CASE SUBSTR(A.SYSTEM_ITEMCODE,6,2) WHEN ('PI') THEN 'OIP' WHEN ('PF') THEN 'OPF' ELSE 'OWL' END )AS LEGAL_ENTITY " & _
"FROM xxdhl_pf_batch_pricing A JOIN fnd_user B ON A.CREATED_BY = B.USER_ID " & _
"JOIN fnd_user C ON A.LAST_UPDATED_BY = C.USER_ID WHERE "
If (ActiveSheet.cmbLE.Text) <> "" Then
strSQL = strSQL & " (CASE SUBSTR(A.SYSTEM_ITEMCODE,6,2) WHEN ('PI') THEN 'OIP' WHEN ('PF') THEN 'OPF' ELSE 'OWL' END )='" & ActiveSheet.cmbLE.Text & "'"
End If
If (ActiveSheet.cmbProduct.Text) <> "" Then
If (ActiveSheet.cmbLE.Text) <> "" Then
strSQL = strSQL & " AND A.SYSTEM_ITEMCODE='" & ActiveSheet.cmbProduct.Text & "'"
Else
strSQL = strSQL & " A.SYSTEM_ITEMCODE='" & ActiveSheet.cmbProduct.Text & "'"
End If
End If
If (ActiveSheet.txtBatch.Text) <> "" Then
If (ActiveSheet.cmbLE.Text) <> "" Or (ActiveSheet.cmbProduct.Text) <> "" Then
strSQL = strSQL & " AND A.BATCH_NUMBER='" & ActiveSheet.txtBatch.Text & "'"
Else
strSQL = strSQL & " A.BATCH_NUMBER='" & ActiveSheet.txtBatch.Text & "'"
End If
End If
If (ActiveSheet.txtfromdt.Text) <> "" Then
If (ActiveSheet.txtfromdt.Text) <> "" And (ActiveSheet.txtTodt.Text) <> "" Then
Else
strSQL = strSQL & " AND TRUNC(A.EFFECTIVE_FROM) BETWEEN TO_DATE('" & ActiveSheet.txtfromdt.Text & "','DD-MON-YYYY') AND TO_CHAR(SYSDATE ,'DD-MON-YYYY') "
End If
End If
If (ActiveSheet.txtfromdt.Text) <> "" And (ActiveSheet.txtTodt.Text) <> "" Then
If (ActiveSheet.cmbLE.Text) <> "" Or (ActiveSheet.cmbProduct.Text) <> "" Or (ActiveSheet.txtBatch.Text) <> "" Then
strSQL = strSQL & " AND TRUNC(A.EFFECTIVE_FROM) BETWEEN TO_DATE('" & ActiveSheet.txtfromdt.Text & "','DD-MON-YYYY') AND TO_DATE('" & ActiveSheet.txtTodt.Text & "','DD-MON-YYYY') "
Else
strSQL = strSQL & " TRUNC(A.EFFECTIVE_FROM) BETWEEN TO_DATE('" & ActiveSheet.txtfromdt.Text & "','DD-MON-YYYY') AND TO_DATE('" & ActiveSheet.txtTodt.Text & "','DD-MON-YYYY') "
End If
End If
'Open Recordset
Set recset.ActiveConnection = con
If recset.State = adStateOpen Then recset.Close
recset.CursorLocation = adUseClient
recset.Open strSQL, con, adOpenKeyset, adLockOptimistic
For iCols = 0 To recset.Fields.Count - 1
Worksheets("Sheet2").Cells(1, iCols + 1).Value = recset.Fields(iCols).Name
Next
'Copy the data
If recset.RecordCount > 0 Then
Sheets("Sheet2").Range("A2").CopyFromRecordset recset
Else
MsgBox "No Data Available", vbExclamation + vbOKOnly, ""
Exit Sub
End If
recset.Close
con.Close
errHandler:
If Err.Number = -2147467259 Then
MsgBox "Please check for the xx connectivity ", vbExclamation + vbOKOnly
Exit Sub
End If
End Sub
Actual result - 6/5/2015 4:12:47 PM but In Excel - 42160.67554
Please help :(
Which columns are you referring to as you have a mixture of logic when it comes to dates in your SQL query.
CREATION_DATE and LAST_UPDATE_DATE should work fine and simply need formatting like #KazimierzJawor said. Something like:-
Range("B5:B10, D5:D10").NumberFormat = "m/d/yyyy h:mm:ss AM/PM"
If you are referring to MFR_DATE, EXPIRY_DATE and EFFECTIVE_FROM columns, then you should remove the TO_CHAR functions as this is forcing the data to be text. Once you have removed the functions, you should be able to format those columns using the same technique as shown above.

I am having problems with variables in SQL statements

I am kind of a newbie with VBA. I have this routine that has three recordsets. The first two will get the part number and the date, the last one will give the OH inventory for that date and part number. I then use the three variables in an append query to create an inventory table per day. I am getting stuck while opening the third recordset, as I am coming up with no records, but I know that there is OH inventory for the first item on the first date. Here is the definition of the SQL string with the variables:
StrSQL2 = " SELECT top 1 "
StrSQL2 = StrSQL2 & " dbo_ViewQtStock.KIPRODMAG, "
StrSQL2 = StrSQL2 & " dbo_ViewQtStock.DTTRANS, "
StrSQL2 = StrSQL2 & " dbo_ViewQtStock.QTSTOCK "
StrSQL2 = StrSQL2 & " FROM dbo_ViewQtStock "
StrSQL2 = StrSQL2 & " WHERE (((dbo_ViewQtStock.KIPRODMAG)=" & KIPRODMAG & ") "
StrSQL2 = StrSQL2 & " AND ((dbo_ViewQtStock.DTTRANS)<='" & DTTRANS & "')) "
StrSQL2 = StrSQL2 & " ORDER BY dbo_ViewQtStock.DTTRANS DESC "
The part number KIPRODMAG is defined as an integer and the date DTTRANS as string (varchar type on server). I used the Debug.Print to he me figure some things out:
Debug.Print DTTRANS = 20130501
Debug.Print KIPRODMAG = 1
Debug.Print StrSQL2 =
SELECT top 1
dbo_ViewQtStock.KIPRODMAG,
dbo_ViewQtStock.DTTRANS,
dbo_ViewQtStock.QTSTOCK
FROM dbo_ViewQtStock
WHERE (((dbo_ViewQtStock.KIPRODMAG)=0)
AND ((dbo_ViewQtStock.DTTRANS)<=''))
ORDER BY dbo_ViewQtStock.DTTRANS DESC
I cannot unerstand why it assigns null in lieu of 20130501 and 0 in lieu of 1. Can anyone out there help me figure this out?
In case it is required, here is the complete routine:
Option Compare Database
Public Sub Stock1()
Dim cnn1 As ADODB.Connection
Dim cnn2 As ADODB.Connection
Dim cnn3 As ADODB.Connection
Set cnn1 = CurrentProject.Connection
Set cnn2 = CurrentProject.Connection
Set cnn3 = CurrentProject.Connection
Dim RS_IPRODMAG As New ADODB.Recordset
Dim RS_Date As New ADODB.Recordset
Dim RS_Stock As New ADODB.Recordset
RS_IPRODMAG.ActiveConnection = cnn1
RS_Date.ActiveConnection = cnn2
RS_Stock.ActiveConnection = cnn3
Dim StrSQL0 As String
Dim StrSQL1 As String
Dim StrSQL2 As String
Dim StrSQL3 As String
Dim DTTRANS As String
Dim KIPRODMAG As Integer
Dim QTSTOCK As Integer
'_____________________________________________________________________________
'RS_IPRODMAG
StrSQL0 = " SELECT "
StrSQL0 = StrSQL0 & " dbo_IPRODMAG.KIPRODMAG "
StrSQL0 = StrSQL0 & " FROM dbo_IPRODMAG "
StrSQL0 = StrSQL0 & " INNER JOIN dbo_VIProduit "
StrSQL0 = StrSQL0 & " ON dbo_IPRODMAG.KIPRODUIT = dbo_VIProduit.KIPRODUIT "
StrSQL0 = StrSQL0 & " WHERE (((dbo_VIProduit.flstock)=1) "
StrSQL0 = StrSQL0 & " AND ((dbo_VIProduit.fllocation)=1)) "
StrSQL0 = StrSQL0 & " ORDER BY dbo_IPRODMAG.KIPRODUIT "
'_____________________________________________________________________________
'RS_Date
StrSQL1 = " SELECT dbo_View_ITrans_Periodes.DTTRANS "
StrSQL1 = StrSQL1 & " FROM dbo_View_ITrans_Periodes "
StrSQL1 = StrSQL1 & " WHERE (((dbo_View_ITrans_Periodes.noannee)=2014)) "
'_____________________________________________________________________________
'RS_Stock
StrSQL2 = " SELECT top 1 "
StrSQL2 = StrSQL2 & " dboViewQtStock.KIPRODMAG, "
StrSQL2 = StrSQL2 & " dboViewQtStock.DTTRANS, "
StrSQL2 = StrSQL2 & " dboViewQtStock.QTSTOCK "
StrSQL2 = StrSQL2 & " FROM dboViewQtStock "
StrSQL2 = StrSQL2 & " WHERE (((dboViewQtStock.KIPRODMAG)=" & KIPRODMAG & ") "
StrSQL2 = StrSQL2 & " AND ((dboViewQtStock.DTTRANS)<='" & DTTRANS & "')) "
StrSQL2 = StrSQL2 & " ORDER BY dboViewQtStock.DTTRANS DESC "
'______________________________________________________________________________
'Append to STOCK
StrSQL3 = " INSERT INTO STOCK ( KIPRODMAG, DTTRANS, QTSTOCK ) "
StrSQL3 = StrSQL3 & " SELECT "
StrSQL3 = StrSQL3 & " & KIPRODMAG & ", "
StrSQL3 = StrSQL3 & " '" & DTTRANS & "'" & ", "
StrSQL3 = StrSQL3 & " '" & QTSTOCK & "'" & " "
'_____________________________________________________________________________
'Open recordset RS_IPRODMAG
RS_IPRODMAG.Open StrSQL0
RS_IPRODMAG.MoveFirst
'_____________________________________________________________________________
'Start of loop #1
Do While Not RS_IPRODMAG.EOF
KIPRODMAG = RS_IPRODMAG.Fields(0).Value
'_____________________________________________________________________________
'Open recordset RS_Date
RS_Date.Open StrSQL1
RS_Date.MoveFirst
'____________________________________________________________________________
'Start of loop #2
Do While Not RS_Date.EOF
DTTRANS = RS_Date.Fields(0).Value
'_________________________________________________________________________________
'Open recordset RS_STOCK
Debug.Print DTTRANS
Debug.Print KIPRODMAG
Debug.Print StrSQL2
DoCmd.RunCommand acCmdDebugWindow
RS_Stock.Open StrSQL2
QTSTOCK = RS_Stock.Fields(2).Value
'_____________________________________________________________________________________
'Append table STOCK
DoCmd.RunSQL StrSQL3
RS_Stock.Close
RS_Date.MoveNext
Loop
end of loop #2
'_____________________________________________________________________________________
RS_Date.Close
RS_IPRODMAG.MoveNext
Loop
'END of loop #1
'______________________________________________________________________________________
RS_IPRODMAG.Close
cnn1.Close
End Sub
You never give values your variables. You need to do this:
...
Dim KIPRODMAG As Integer
Dim QTSTOCK As Integer
DTTRANS = "20130501"
KIPRODMAG = 1
....
This is a debug statement which will print in your debug window:
Debug.Print DTTRANS = 20130501
Debug.Print KIPRODMAG = 1
It will tell you whether the statement reseolves to true or false, not set your variable values.

VBA Contains Function

I'm currently making an Excel function that connects to an SQL server and retrieves data as long as it matches the given criteria.
Public Function VehModelUnitsCount(VehModel As String, fran As String, Site As Integer, SaleType As String, StartDate, EndDate, New As Integer) As Variant
Application.Volatile
If adoCN Is Nothing Then Call SetUpConnection
Set adoRS = New ADODB.Recordset
EvoStartDate = Format(StartDate, "yyyy/mm/dd")
EvoEndDate = Format(EndDate, "yyyy/mm/dd")
strSQL = "SELECT COUNT(*) As RCOUNT FROM CARTYPES RIGHT OUTER JOIN CARS ON CARTYPES.Description = CARS.Type LEFT OUTER JOIN CARS2 ON CARS.[Stock Number] = CARS2.[Stock Number]" & Chr(13)
strSQL = strSQL & "WHERE (CARTYPES.NewSale = " & New & " )" & Chr(13)
strSQL = strSQL & "AND (CARTYPES.Franchise = '" & fran & "')" & Chr(13)
strSQL = strSQL & "AND (CARTYPES.Site = " & Site & ")" & Chr(13)
strSQL = strSQL & "AND (CARTYPES.SaleTypeDesc = '" & SaleType & "')" & Chr(13)
strSQL = strSQL & "AND (CARS2.InvoiceDate BETWEEN '" & StartDate & "' AND '" & EndDate & "')" & Chr(13)
strSQL = strSQL & "AND (CARS.Invoiced = '1')" & Chr(13)
Rem strSQL = strSQL & "AND (CARS.Model = '" & VehModel & "')" & Chr(13)
[THIS ONE] - strSQL = strSQL & "AND (CARS.Model CONTAINS '" & VehModel & "')" & Chr(13)
adoRS.Open strSQL, adoCN, adOpenForwardOnly, adLockReadOnly
VehModelUnitsCount = adoRS.Fields("RCOUNT").Value
adoRS.Close
End Function
The string marked with [THIS ONE] is the one I am struggling with, I need to find out whether or not the cell contains the given string, but apparently using 'CONTAINS' doesn't work.
Any help on completing this would be amazing.
Thank you.
You could try -
strSQL = strSQL & "AND (CARS.Model LIKE '%" & VehModel & "%')" & Chr(13)

Resources