Access VBA SQL query searching between dates - sql

I have a some VBA code that takes in a date from and date to fields from two date picker values in textboxes.
However, when searching between the two dates I receive the 'Enter Parameter Value' prompt asking for input.
Dim SQLAllReject As String
Dim strDateFrom As String
Dim strDateTo As String
strDateFrom = Format(txtDate.Value, "mm/dd/yyyy")
strDateTo = Format(txtDateTo.Value, "mm/dd/yyyy")
When running directly in the Query Design wizard, searching between dates works fine:
WHERE (((XXXXXXXXXXXXXXXXXXXX.Date) Between #10/1/2021# And #10/27/2021#))
What is wrong here? How can I force Access/VBA to take the dates I've specified and search between them and NOT display the 'Enter Parameter Value' prompt?
When I debug the query and step through, it gives exactly the same dates as running it in Query Design view.
FYI if I use one date and the LIKE operator, this works fine.
SQLAllReject = "SELECT dbo_vw_busobj_file_rejections_load_access_temp5_copy.HashKey AS [ID], dbo_vw_busobj_file_rejections_load_access_temp5_copy.Reject_Date AS [Date], " & _
"FROM dbo_vw_busobj_file_rejections_load_access_temp5_copy " & _
"WHERE (((dbo_busobj_file_rejections_load_access_temp5_copy.Reject_Date) Between #" & strDateFrom & "# And #" & strDateTo & "#)) " & _
"ORDER BY dbo_vw_busobj_file_rejections_load_access_temp5_copy.Reject_Date DESC;"

Ok I somehow fixed it... the query string was trying to select from a view rather than the table and for some odd reason it was causing the parameter prompt.
I have changed dbo_vw_busobj_file_rejections_load_access_temp5_copy to dbo_busobj_file_rejections_load_access_temp5_copy table and managed to get it to work after doing some string to date conversion when selecting dates from the textboxes.

Related

Problem using where with date in SQL Statement

I am trying to execute an SQL statement in a VBA script. I have gotten the script to run, but it ignores the where with a date filter.
I have researched and tried every option I can find, but just cant seem to get it to work.
Set rs = conn.Execute("Select [adjustment_number], [status], [tax_adjusted],[amount], [gl_date],[creation_date],[apply_date],[comments],[type],[adjustment_type],[dbo].[Code_Combinations].[segment1], [dbo].[Code_Combinations].[segment10],[dbo].[Code_Combinations].[segment11],[dbo].[Code_Combinations].[segment12],[dbo].[Code_Combinations].[code_combination] FROM [dbo].[AR_ADJUSTMENTS_ALL] " & _
"left outer join [dbo].[Code_Combinations] on [dbo].[AR_ADJUSTMENTS_ALL].[CODE_COMBINATION_ID] = [dbo].[Code_Combinations].[CODE_COMBINATION_ID] where [gl_date] >= " & gldate & ";")
(Copying this from my comment above, into an answer, since this solved your problem)
SQL Server? Put single quotes around your date in the WHERE clause.
where [gl_date] >= '" & gldate & "';"
Assumes that gldate is a valid date, and [gl_date] is of a date datatype.

MS Access VBA, not getting results when running DoCmd to find a record

I am not a programmer by any means but I am trying to get a small data collection database going. I need to find a record based on input. Ive got two criteria that I want it to find, and if both arent found together, it is supposed to create a new record (with both fields filled out to prevent duplication of the pair). First criteria is that it needs to look for a date. I figured that one out already, here is the code.
Dim Date1 As String
Date1 = Text6.Value
DoCmd.OpenForm "Data", , , "Data![ShiftDate] = #" & Date1 & "#"
Works like a charm. Now, I tried to add the second criteria in. The second criteria pulls from a listbox, either Day or Night. Then, it is supposed to search my data fields for that same criteria in a list box on my Data! form.
Dim Date1 As String
Dim Shift1 As String
Date1 = Text6.Value
Shift1 = List12.Column(1)
MsgBox Shift1
DoCmd.OpenForm "Data", , , _
"Data![ShiftDate] = #" & Date1 & "# AND Data![Shift] ='" & Shift1 & "'"
the msgbox was just to verify that it is pulling the right words, day or night. Everything works great, but instead of pulling a record on the right date, and with the right shift, I get blank records. I tried taking out the first half of the where statement to isolate the shift part and still just cannot get it to find a record. I have no idea what I am doing wrong.
It seems that you already have a form.
I recommend you trying this:
Add a button with a click event to the form and add following code to the click event:
dim rs as dao.recordset
set rs = currentdb.openrecordset ("SELECT * FROM [yourtable] WHERE ('ShiftDate' = '" & [yourParameter] & "' AND 'Shift' = '" & [your2ndParameter] & "')")
if rs.eof then
' here NO record is found
currentdb.execute ("INSERT INTO [yourtable] ('ShiftDate', 'Shift') VALUES ('" & [yourParameter] & "', '" & [your2ndParameter] & "')")
else
' here a record is found
endif
Since your ShiftDate is a date you need to convert your date to a SQL date Format, like this:
Function SQLDatum(Datumx) As String
If IsDate(Datumx) Then
SQLDatum = Format(CDate(Datumx), "\#yyyy-mm-dd\#", vbMonday, _
vbFirstFourDays)
Else
SQLDatum = ""
End If
End Function
In your command
DoCmd.OpenForm "Data", , , "Data![ShiftDate] = #" & Date1 & "# AND ...
You open a form Data but at the same time you specify a filter by referring to the form which is being opened with Data![ShiftDate]. This is very strange, since the filter must be applied to the data source. I would simply write
DoCmd.OpenForm "Data", , , "ShiftDate= #" & Date1 & "# AND Shift= '" & Shift1 & "'"
by referring to the table columns of the data source (on the left side of =).
Note that the column Shift must be a text column. If it was some number, you would have to drop the single quotes and pass it a corresponding id.

MS Access SQL query within VBA code

I need a second set of eyes on this SQL query embedded in the VBA code. I'm making an MS Access app that returns a dataset based on the to & from date criteria set by the user in the specific date picker boxes. The sql query that you see actually has been tested statically within MS Access query design view. I tested it with actual dates where you see the Me.from_filter and Me.to_filter. It worked perfectly! If you chose something like from 1/1/2015 to 5/1/2015 it returns columns of all the months you need. Perfect. Now when I embed it in the VBA code and assign it to a control variable, I get the "Run-time error '2342': A RunSQL action requires an argument consisting of an SQL statement." Can someone please eyeball this and tell me what might be wrong?
Option Compare Database
Option Explicit
Dim strSQL As String
Private Sub Command0_Click()
If IsNull(Me.from_filter) Or IsNull(Me.to_filter) Then
MsgBox "You have not entered a start date or end date"
Else
strSQL = "TRANSFORM Sum(dbo_ASSET_HISTORY.MARKET_VALUE) AS SumOfMARKET_VALUE " _
& "SELECT [dbo_FIRM]![NAME] AS [FIRM NAME], dbo_FUND.CUSIP, dbo_FUND.FUND_NAME, dbo_FUND.PRODUCT_NAME " _
& "FROM (dbo_ASSET_HISTORY INNER JOIN dbo_FIRM ON dbo_ASSET_HISTORY.FIRM_ID = dbo_FIRM.FIRM_ID) INNER JOIN dbo_FUND ON dbo_ASSET_HISTORY.FUND = dbo_FUND.FUND " _
& "WHERE (((dbo_FIRM.Name) Like 'Voya F*') And ((dbo_ASSET_HISTORY.PROCESS_DATE) >= #" & Me.from_filter & "# And (dbo_ASSET_HISTORY.PROCESS_DATE) <= #" & Me.to_filter & "#)) " _
& "GROUP BY [dbo_FIRM]![NAME], dbo_FUND.CUSIP, dbo_FUND.FUND_NAME, dbo_FUND.PRODUCT_NAME " _
& "PIVOT [dbo_ASSET_HISTORY]![ASSET_YEAR] & '-' & [dbo_ASSET_HISTORY]![ASSET_MONTH];"
DoCmd.RunSQL (strSQL)
End If
End Sub
RunSQL is for running action queries like update, insert, select into, delete, etc as per Microsoft definition https://msdn.microsoft.com/en-us/library/office/ff194626.aspx , you should probably use OpenQuery or similar to run your query.

Microsoft Query in Excel VBA - how to pass date filters

I am really hoping someone here could help me with the issue I have spent hours trying to fix with no result.
I am trying to establish a data connection with a csv file using MS query in Excel VBA. I need to filter the data out from the csv file into the spreadsheet by applying a date filter on a certain column. When the date is fixed (i.e. hardcoded in VBA), the connection works absolutely fine. However, I would like the date to be a user input and that's where I am facing problems. Basically, I am not sure how to pass a date variable to the connection.
When the macro works fine, the SQL statement looks like this:
.CommandText = "SELECT * FROM " & csvName & " WHERE SECTYPE='GS' AND LAST TRADED DATE={ts '2016-01-29 00:00:00'}"
When I try to pass the date via variable sValnDate, I get 'SQL syntax error':
.CommandText = "SELECT * FROM " & csvName & " WHERE SECTYPE='GS' AND LAST TRADED DATE={ts " & sValnDate & "}"
I have tried several configurations of the variable. I have tried to pass it as a date, a string exactly as in the correct command, a date formatted as required in the correct command, keeping and removing the curly brackets with each format of the variable etc, but nothing worked.
I have just presented here 1 statement to keep things simple. However, if you need to see the entire block (not more than 15-20 lines), please let me know.
Thanks in advance
PS: just looked at the preview. Somehow `` around LAST TRADED DATE have been removed here.
Assuming that sValnDate is a string that looks like 2016-01-29 00:00:00 then you are simply missing the ticks (aka single quotes or Chr(39)).
.CommandText = "SELECT * FROM " & csvName & _
" WHERE [SECTYPE]='GS' AND [LAST TRADED DATE]={ts '" & sValnDate & "'}"
If sValnDate is an actual date then format it like,
.CommandText = "SELECT * FROM " & csvName & _
" WHERE [SECTYPE]='GS' AND [LAST TRADED DATE]={ts '" & _
Format(sValnDate, "yyyy-mm-dd hh:mm:ss" & "'}"

Updating a field dependent on a date range in Access with VisualBasic and SQL

A friend and I have been trying for hours with little progress to a get a piece of code right for an invoicing system we're designing as a project.
We are trying to update the field InvoiceNo to a value (worked out earlier in the VisualBasic code), where the CustomerNo is the is a specific value and the FinishDate is between two dates. At first I was trying to use TO_DATE but then we realized that wasn't the same in the SQL that Access uses (after much searching).
This has been the simple statement I've been using to just test and try to get something working to then translate into VisualBasic and put in our variables. It's a little easier to read so I thought I'd provide it.
UPDATE tblJob SET tblJob.InvoiceNo = '8' WHERE tblJob.CustomerNo = '1' AND (tblJob.FinishDate BETWEEN cdate(format('08/09/2013', '##/##/####')) AND cdate(format('03/10/2013', '##/##/####')));
I have a feeling after looking at a few examples that our date is meant to be without an forward slashes. So I tried that and it wasn't working either.
Here's the VisualBasic code that has come out of all of this, it's exactly the same but using some variables rather than our set values that I've been using for testing.
DoCmd.RunSQL ("UPDATE tblJob SET tblJob.InvoiceNo = '" & newInvoiceNo & "' WHERE tblJob.CustomerNo = '" & VbCustNo & "' AND (tblJob.FinishDate BETWEEN cdate(format('" & Forms![frmMainMenu][txtFirstDate] & "', '##/##/####')) AND cdate(format('" & Forms![frmMainmenu][txtEndDate] & "', '##/##/####')));")
We had a look at: Convert a string to a date in Access and it helped us realize that it was cdate(format()) rather than TO_DATE as it is in Oracle. But we just can't seem to get it to run properly, any help would be much appreciated.
If you will be running the query from within an Access application session, you can let the db engine use the Access expression service to grab the values from the text boxes on your form.
Dim db As DAO.Database
Dim strUpdate As String
strUpdate = "UPDATE tblJob" & vbCrLf & _
"SET InvoiceNo = '" & newInvoiceNo & "'" & vbCrLf & _
"WHERE CustomerNo = '" & VbCustNo & "'" & vbCrLf & _
"AND FinishDate BETWEEN Forms!frmMainMenu!txtFirstDate AND Forms!frmMainmenu!txtEndDate;"
Debug.Print strUpdate
Set db = CurrentDb
db.Execute strUpdate, dbFailOnError
Set db = Nothing
However, if you prefer to build the literal date values from those text boxes into your UPDATE statement, you can use Format().
"AND FinishDate BETWEEN " & _
Format(Forms!frmMainmenu!txtFirstDate, "\#yyyy-m-d\#") & _
" AND " & Format(Forms!frmMainmenu!txtEndDate, "\#yyyy-m-d\#") & ";"
Either way, using a string variable to hold your UPDATE statement gives you an opportunity to examine the completed statement you're asking the db engine to execute.
You can view the output from Debug.Print in the Immediate window (go there with Ctl+g). For troubleshooting, you can copy the statement text from there and then paste it into SQL View of a new Access query.