MS Access reference issue with form fields - vba

Hi there this is my goal, I have a for with a start date(start_Date) and end date(end_Date) field and a report which has a crosstab query as a record source. I want to be able to sort the data on my report based on the dates given on the form. I tried 3 different approaches.
Running a macro and opening the report with a where condition in which case Access would complain and say "[Reports]![AuditPTETotal]![Date] is not a valid reference"
Setting the "where condition" of my report through VBA. Another reference error but this time, it says that my forms fields are invalid.
Private Sub ViewReport_Click()
Dim strWhere As String
If Not IsNull(Me.start_Date) Then
strWhere = strWhere & " AND [Reports]![AuditPTETotal]![Date] >=#" & [Forms]! [AuditPTETotals]![start_Date] & "# "
End If
If Not IsNull(Me.end_Date) Then
strWhere = strWhere & " AND [Reports]![AuditPTETotal]![Date] <=#" & [Forms]! [AuditPTETotals]![end_Date] & "# "
End If
DoCmd.OpenReport "AuditPTETotal", acViewNormal, , strWhere
End Sub
And finally, passing in my forms values into the query. None of these approaches have worked for me and I really need to get this done. I am out of option. Any help would be appreciated.
Query
PARAMETERS [Forms]![AuditPTETotals]![start_Date] DateTime, [Forms]![AuditPTETotals]! [end_Date] DateTime;
TRANSFORM Sum(ScrapCollection.PTEtotal) AS SumOfPTEtotal
SELECT ScrapCollection.Date, ScrapCollection.regNum
FROM ScrapCollection INNER JOIN (ScrapTireType INNER JOIN ScrapCollectionTireType ON (ScrapTireType.scrapTireTypeID = ScrapCollectionTireType.scrapTireTypeID) AND (ScrapTireType.scrapTireTypeID = ScrapCollectionTireType.scrapTireTypeID)) ON ScrapCollection.scrapCollectionID = ScrapCollectionTireType.scrapCollectionID
WHERE (((ScrapCollection.Date) Between [Forms]![AuditPTETotals]![start_Date] And [Forms]![AuditPTETotals]![end_Date]))
GROUP BY ScrapCollection.Date, ScrapCollection.regNum
PIVOT ScrapTireType.description;

If you want to limit the results of a crosstab by using a form, you must have parameters:
PARAMETERS [Forms]![AForm]![text0] DateTime, [Forms]![AForm]![text2] DateTime;
TRANSFORM Count(Table1.AKey) AS CountOfAKey
SELECT Table1.AText
FROM Table1
WHERE (((Table1.ADate) Between [Forms]![AForm]![text0] And [Forms]![AForm]![text2]))
GROUP BY Table1.AText
PIVOT Table1.ADate;

Related

Access VBA SQL query searching between dates

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.

VBA Query returning nulls

Using the query builder in Access I am able to find the total, but I need to find the total using the vba code builder. The code given here gives me a null value.
Dim rst As DAO.Recordset
Dim dbs As Database
Dim strSQL As String
Set dbs = CurrentDb
strSQL = "SELECT Sum(GiftRcvd.Rcvdamount) AS SumOfRcvdamount FROM OurEvents INNER JOIN GiftRcvd ON OurEvents.EventName = GiftRcvd.EventName " & _
"WHERE ((([OurEvents].[EventDate])>" & Me.DateFrom.Value & " And ([OurEvents]![EventDate])< " & Me.DateTo.Value & "));"
Set rst = dbs.OpenRecordset(strSQL)
SumOfRcvdamount = rst![SumOfRcvdamount]
MsgBox SumOfRcvdamount
It's likely that your query is returning an empty recordset. Assuming you have data, this most likely means that your HAVING clause is filtering out the records you want.
As I remember, date literals in Access have to be in the format #1/30/2019#: a clause in the form [EventDate] > 1/30/2019 will not evaluate the way you want.
So try bracketing those date parameters with #:
[OurEvents].[EventDate])> "#" & Me.DateFrom.Value & "#"
Strictly speaking, you should avoid assembling queries from strings (due to the possibility of SQL Injection attacks): you should instead parameterize them and pass parameter values. BUT, that's harder to do in Access than in other forms of SQL.
You have to format your date values to valid string expressions:
"WHERE ((([OurEvents].[EventDate])> #" & Format(Me.DateFrom.Value, "yyyy\/mm\/dd") & "# And ([OurEvents]![EventDate])< #" & Format(Me.DateTo.Value, "yyyy\/mm\/dd") & "#));"

MS Access VBA SQL SELECT * INTO tempTbl WHERE Stuff="" AND OtherStuff BETWEEN Date Range

I have a form with one text box, two combo boxes (dropdowns), and two text boxes with input masks for mm/dd/yyyy 99/99/0000;0;_
I am attempting to use all of these fields as filters for a subform.
I have the controls set to fire after update and run a sub that builds a SELECT * INTO sql string for a temp Table that is then sourceobject'ed back to the subform.
In code I have for each control I have code building a snippet of the Where statement for the final sql. the snippet grows as needed, is labeled "Filter"
Some other non-Finished Code....
If Not IsNull(txtDateFrom) Then
If i > 1 Then Filter = Filter & " AND " & "([Date_LastSaved] >= " & Me.txtDateFrom & ")" & " And " & "([Date_LastSaved] <= " & Me.txtDateTo & ")"
End If
Dim sql As String
sql = "SELECT * INTO tmpTable FROM tblReview"
If Not IsNull(Filter) Then
sql = sql & " WHERE " & Filter
End If
My issue and question is that I am testing this one specific situation where there will be Filter = Filter & " AND " & "DATE_STUFF"
where the final sql looks like...
SELECT * INTO tmpTable FROM tblReview WHERE ReviewStatus = 'Quoted' AND ([Date_LastSaved] >= 09/12/2018) And ([Date_LastSaved] <= 10/16/2018)
which should have some result with the test data. Yet, the tmpTable is empty.
This is only happening when I apply a date range criteria.
I tried BETWEEN but could not nail down the syntax.
Any insight is greatly appreciated, Thanks!
UPDATE:
Answer:
If i > 1 Then Filter = Filter & " AND " & "([Date_LastSaved] >= #" & Me.txtDateFrom & "#)" & " And " & "([Date_LastSaved] <= #" & Me.txtDateTo & "#)"
If you want to use dates then they must be quoted. If you just say 10/16/2018 then you are dividing the integer 10 by 16 by 2018 which will yield an integer zero. It will then convert the dates to an integer to do the compare, which will yield a much bigger number, and thus you get no rows.
Any date testing should always be done using date types rather than strings. I think in msaccess you can surround it in #, but not sure. Just research this.

Running an IF statement in MS VBA using a similar field from two tables

I am trying to set a quantity value based on a sum of the current quantity and then subtracting an amount based on a quantity value in another table.
My current thought process is: If QuantityA is less than or equal to Quantity B then subtract QuantityA from Quantity B.
I am no expert on SQL and MS VBA, so I was wondering how I can make an if statement with the two different tables.
Private Sub Command23_Click()
If QuantityA <= QuantityB Then
QuantityB = QuantityB - QuantityA
Else
MsgBox "You can not hire that many" & ToolName & "as there is only" & [DEPARTMENT TOOLS (stocked)].Quantity & "available"
End If
MsgBox "Your hire request has been successful"
End Sub
Any help would be appreciated
You can achieve what you're asking by opening a recordset containing the results of a query and comparing the values returned by the query. In order to restrict the query to the proper quantities you need to pass in the ID of the tool you are checking.
#June7 is correct about saving calculated data. The only time you would want to save it is if you are keeping a log of events or if speed of join queries becomes an issue (unlikely given proper DB structure)
toolId might be stored in a text box control for example
Function Something_Click(toolId as string)
Dim rs as Recordset
' create a recordset containing data from the two tables
Set rs = CurrentDB.OpenRecordset("SELECT A.TOOL_QTY AS TOOL_QTY_A, " _
& " B.TOOL_QTY AS TOOL_QTY_B, A.TOOLNAME AS TOOLNAME" _
& " FROM TABLE1 AS A " _
& " INNER JOIN TABLE2 AS B ON A.TOOL_ID = B.TOOL_ID" _
& " WHERE A.TOOL_ID = '" & toolId & "'")
' compare the values in the table
If rs![TOOL_QTY_A] <= rs![TOOL_QTY_B] Then
' your true condition, for example
' MsgBox "Success"
Else
' your false condition, for example
' MsgBox "Oops, not enough of " & rs![TOOLNAME]
End If
' close the recordset
rs.close
End Function

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.