SQL VBA issue when converting Query to Module (1 Viewer)

Trevor G

Registered User.
Local time
Today, 09:07
Joined
Oct 1, 2009
Messages
2,341
I am trying to convert a query SQL code to use in a Module to run through VBA but I am encountering an issue with Where statement. what I have in the Query is indicated below:

SELECT *
FROM TempImportedOld
WHERE (((TempImportedOld.ThisYear)=Year(DateAdd("yyyy",-1,Date()))));

Trying to use this in a module as follows:

Sub createQuery3()
Dim qdfNew As DAO.QueryDef
Dim strSQL As String
Dim strSelect1 As String

strSelect1 = "SELECT * FROM TempImportedOld " & _
" WHERE TempImportedOld.ThisYear='Year(DateAdd(""yyyy"",-1,Date()))'"
strSQL = strSelect1
With CurrentDb
.QueryDefs.Delete ("My_Query") 'Look to delete the query
Set qdfNew = .CreateQueryDef("My_Query", strSQL) 'Create the query
End With
DoCmd.OpenQuery "My_Query"
End Sub

When I run this it will fail as in the criteria of the query it shows me this with a single quote mark. 'Year(DateAdd("yyyy",-1,Date()))'

I have attached a copy of the database if someone can point me in the right direction that would be very helpful.
 

Attachments

  • TempQuery1.accdb
    420 KB · Views: 68

spikepl

Eledittingent Beliped
Local time
Today, 10:07
Joined
Nov 3, 2010
Messages
6,142
Make your query the way you want in the query designer. Inspect the SQL and compare with your strSQL in the Immediate window.
 

Trevor G

Registered User.
Local time
Today, 09:07
Joined
Oct 1, 2009
Messages
2,341
Thank you for your advice, I have adjusted the SQL statement and it now works in the way I want it to, so I can now take it to the next level.
 

Pat Hartman

Super Moderator
Staff member
Local time
Today, 04:07
Joined
Feb 19, 2002
Messages
43,626
Embedding SQL strings in VBA is not taking it to the next level. SQL strings in code cause database bloat. It is better to leave them as querydefs.
 

Users who are viewing this thread

Top Bottom