MS access sum results between two dates as text box in form - sql

I issue following query in SQL and works fine
SELECT SUM(goudOpkoop.winst)
FROM goudOpkoop
WHERE goudOpkoop.date
BETWEEN '2015-1-10' AND '2015-1-22'
I would like to have the results in a Form in Textbox 3 (name Text183) when last of two dates, one in Textbox 1 (name Text179) and other in textbox 2 (name Text181) have been picked.
I think I would need to use AfterUpdate code builder for Textbox 2 and issue there the query to eventually show results in Textbox 3.
I have already linked with SQL server.
Information: ODBC;DSN=Essence Test;;TABLE=goudOpkoop
In me not being a professional in VBA I have no clue how to get this working.

Not tested, but should do the trick slightly, unless I made a typo.
Change the format of your 2 dates textboxes in "Short Date", that way you will have a calendar picker and you will ensure that your date have a correct format
Create this sub in your form module :
Private Sub CheckSUM()
Dim RST As Recordset
Dim SQL As String
' Reset the result textbox
Text183.value = ""
' If your 2 date textboxes are not populated, cancel
If Text179.Value = "" or Text181.Value = "" Then Exit Sub
' Prepare the query, with proper formating of the dates
SQL = " SELECT SUM(goudOpkoop.winst) AS mySum " & _
" FROM goudOpkoop " & _
" WHERE goudOpkoop.Date " & _
" BETWEEN '" & Format(Text179.Value, "YYYY-MM-DD") & "' " & _
" AND '" & Format(text181.Value, "YYYY-MM-DD") & "'"
' Execute the query
Set RST = CurrentDb.OpenRecordset(SQL)
' If the query is valid and returned something, we recuperate the value
If Not RST.BOF Then
Text183.Value = RST!mySum
End If
' Cleaning
RST.Close
Set RST = Nothing
End Sub
Then, for your 2 dates textboxes, create an afterupdate event and call the previous sub in them:
Private Sub Text179_AfterUpdate()
CheckSUM
End Sub
Private Sub Text181_AfterUpdate()
CheckSUM
End Sub

Related

MS Access fast Combo Box with VBA

I have a form which has a ComboBox on it that pulls records via ID and displays Name from a linked table. Standard look for values in the form combo box wizard generated. It works perfectly fine, but it takes 3-4 minutes every time to find a single record.
I've been trying to research this and found something that looks useful, but can't seem to get it right.
The code I have at the moment:
Private Sub Combo81_Change()
Dim strText As String
Dim strSelect As String
strText = Nz(Me.Combo81.Text, "")
If Len(strText) > 2 Then
strSelect = "SELECT Name FROM CTable WHERE Name LIKE '*" & strText & "*'; "
Debug.Print strSelect
Me.Combo81.RowSource = strSelect
Me.Combo81.Dropdown
End If
End Sub
I found this code on two forums, this is supposed to do the following: "the key is to not have a Row Source defined for the Combo Box. The row source will be defined as the user starts typing letters. Once they get to 3 letters then the row source of the combo box will be defined and the combo box will be told to dropdown."
When I get to 3 letters, a dropdown appears, but it's blank, it doesn't display any results.
I would like when the user types, e.g. "Smith" only those people with the name Smith come up.
I'm relatively new to Access and the DB I'm using the FE/BE with linked tables to a shared network folder and FE on users Desktops.
Any advice? Or alternatively a different solution as to how take my combo box faster and still keep values unique?
you can use following codes to search value in a combo-box in ms access as user type,
suppose we have a combo-box name org_id in our form, for search a value in org_id we need three event on org_id combo-box. AfterUpdate, LostFocus and KeyPress events.
codes are:
Dim strFilter As String ' Module scope variable used for filter on our combo (org_id)
Private Sub org_id_AfterUpdate()
strFilter = ""
strSQL = "SELECT org_tbl.org_id, org_tbl.org_name, org_tbl.org_code FROM org_tbl" & _
" ORDER BY org_tbl.org_code"
org_id.RowSource = strSQL
End Sub
Private Sub org_id_LostFocus()
strFilter = ""
strSQL = "SELECT org_tbl.org_id, org_tbl.org_name, org_tbl.org_code FROM org_tbl" & _
" ORDER BY org_tbl.org_code"
org_id.RowSource = strSQL
End Sub
Private Sub org_id_KeyPress(KeyAscii As Integer)
strSQL = "SELECT org_tbl.org_id, org_tbl.org_name, org_tbl.org_code FROM org_tbl ORDER BY org_tbl.org_code"
If KeyAscii <> 8 Then ' pressed key is not backspace key
strFilter = strFilter & Chr(KeyAscii)
End If
If IsNull(strFilter) = True Or strFilter <> "" Then
If KeyAscii = 8 Then ' pressed key is backspace key
strFilter = Left(strFilter, (Len(strFilter) - 1))
End If
End If
strSQL = "SELECT org_tbl.org_id, org_tbl.org_name, org_tbl.org_code FROM org_tbl" & _
" WHERE org_name Like '*" & strFilter & "*' ORDER BY org_tbl.org_code"
org_id.RowSource = strSQL
org_id.Dropdown
End Sub
I hope this (answer) helps you.
edit:
you can download sample file from following link:
Access combo box to search as you type sample file

Continue Loop in TextBox to search multiple value from Database, MS Access

I've changed the textbox "enter key behavior", so that everytime I hit enter, textbox will go to the next line,
Project's Form View
When user Click the Button, subform show result for the first line, but then how to get result in every line user input.
Private Sub CountButton_Click()
Dim SQL As String
SQL = "SELECT database.Tracking, database.Date, DateDiff(""d"",[Date],Date()) As Aeging FROM database;"
Me.Query1_subform.Form.RecordSource = SQL
Me.Query1_subform.Form.Requery
End Sub
Do I need to use Loop or VbCrLf or something else to function the textbox
Split textbox value to an array and loop array to build comma-separated string or:
strIN = Replace(Me.textbox, vbCrLf, "','")
If InStrRev(strIN, "','") > 0 Then strIN = Left(strIN, Len(strIN)-3)
SQL = "SELECT database.Tracking, database.Date, DateDiff('d', [Date], Date()) As Aging " & _
"FROM database " & _
"WHERE Tracking IN('" & strIN & "');"
Using a textbox relies on users to be consistent with input - not starting input with a CR and no other extraneous characters input accidentally or otherwise.
More reliable alternative is a multi-select listbox of Tracking values. Code loops through selected items and builds comma-separated string.

Filter subforms date column via main form Date range entry in vba access

I have a form named frmCCAuto which includes my date range i.e. start date and end date text fields with a button to filter date.I have a subform "subCCAuto-Open" (I dont know why my seniors decided to use subform name with '-')whose default view is Datasheet and its record source is pulled from a table tblPayments_Auto. So, I have to filter the records displayed in the subform according to the date range which is in main form. In other words, what I want to have happen is on two unbound text boxes allow users to enter a date range and have the subform filtered to only show records of the date range entered in the main form boxes. Codes I have been working on are:
Private Sub Form_Open(Cancel As Integer)
Dim db As Database
Set db = CodeDb
db.Execute "DELETE * FROM tblPayments_Auto;"
DoCmd.SetWarnings False
DoCmd.OpenQuery "qryPayments_AddAuto" (store procedure: sp_qryPayments_AddAuto )
DoCmd.SetWarnings True
Me.subOpen.Requery
ProcessBtn.Enabled = False
End Sub
Private Sub Filter_Click()
With Forms!frmCCAuto![subCCAuto-Open].Form
.Filter = "[InvoiceDate] BETWEEN #" & Me.StartDate & "# AND #" & Me.EndDate & "#"
.FilterOn = True
End With
End Sub
When I debug my code, it gives me an error saying Microsoft Access can't find the field subCCAuto-Open referred to in your expression. Please help.
Try with the modified syntax:
Private Sub Filter_Click()
With Forms!frmCCAuto.Form![subCCAuto-Open]
.Filter = "[InvoiceDate] BETWEEN #" & Format(Me!StartDate.Value, "yyyy\/mm\/dd") & "# AND #" & Format(Me!EndDate.Value, "yyyy\/mm\/dd") & "#"
.FilterOn = True
End With
End Sub
where frmCCAuto must be the name of the subform control.

Sorting a query by Listbox with multiselect?

My task is create a query that is filtered by the results of a listbox with multiselect. I have a table, named contacts, which has a field named 'Sources'. This is the field that is displayed in my listview. I am sorting by the 'Sources' value
From here, I can multiselect the options, and hit a submit button. When I do so, I get a query but it seems to simply display all of the values.
Therefore, my question is, how can I create a query sorted by the Sources tab? I know that I need a onclick function, but I am very unfamiliar with VB. Any help would be appreciated!
You can modify the following to use your control names. You didn't mention where/how your query is created, but you can merge this code with yours...
Private Sub cmdBuildWhere_Click()
Dim varItem As Variant
Dim strWhere As String
If Me.lstHierarchy.ListIndex < 1 And Me.lstHierarchy.ItemsSelected.Count = 0 Then ' No items selected
MsgBox "You did not select any sources. ", vbOKOnly, "Select Sources"
Exit Sub
End If
strWhere = "WHERE "
For Each varItem In Me.lstHierarchy.ItemsSelected
strWhere = strWhere & "[Sources] = '" & Me.lstHierarchy.Column(0, varItem) & "' Or "
Next varItem
' remove final ' or ' and add Sort
strWhere = Trim(left(strWhere, Len(strWhere) - 4)) & " Order By Sources;"
Debug.Print strWhere
End Sub

#Name? on form after requery in Access 2010

I am using VBA and SQL to re-query my main form based on criteria entered in several controls on a pop up form. As far as I can tell the code is running correctly, the database is re-queried based on the criteria I enter, but 2 of my controls on my main form show as #Name? or blank after re-querying based on the criteria. Anyone know how I can fix this???
The code that runs the re-query is:
Public Sub SuperFilter()
On Error GoTo Err_AdvancedFilter_Click
Dim strSQL As String
Dim strCallNumber As String
Dim strAsgnTech As String
Dim strClientID As String
Dim strCallGroup As String
Dim strPriority As String
Dim strOpenStatus As String
If IsNull(Forms![frmTips&Tricks].txtCallNumber) = False Then
strCallNumber = " (((CallInfo.CallNumber) = forms![frmTips&Tricks].[txtCallNumber])) and "
Else
strCallNumber = ""
End If
If IsNull(Forms![frmTips&Tricks].cboAsgnTech) = False Then
strAsgnTech = " (((CallInfo.AsgnTech) = forms![frmTips&Tricks].[cboasgntech])) and "
Else
strAsgnTech = ""
End If
If IsNull(Forms![frmTips&Tricks].cboClientID) = False Then
strClientID = " (((CallInfo.ClientID) = forms![frmTips&Tricks].[cboClientID])) and "
Else
strClientID = ""
End If
If IsNull(Forms![frmTips&Tricks].cboCallGroup) = False Then
strCallGroup = " (((CallInfo.AsgnGroup) = forms![frmTips&Tricks].[cboCallGroup])) and "
Else
strCallGroup = ""
End If
If IsNull(Forms![frmTips&Tricks].cboPriority) = False Then
strPriority = " (((CallInfo.Severity) = forms![frmTips&Tricks].[cboPriority])) and "
Else
strPriority = ""
End If
If Forms![frmTips&Tricks].optOpenStatus.Value = 1 Then
strOpenStatus = " (((CallInfo.OpenStatus) = True))"
Else
strOpenStatus = " (((CallInfo.OpenStatus) is not null ))"
End If
strSQL = "SELECT CallInfo.CallNumber, CallInfo.ClientID,* " & _
"FROM dbo_HDTechs INNER JOIN ([User] INNER JOIN CallInfo ON User.ClientID = CallInfo.ClientID) ON dbo_HDTechs.TechName = CallInfo.AsgnTech " & _
"WHERE " & strCallNumber & strAsgnTech & strClientID & strCallGroup & strPriority & strOpenStatus & _
"ORDER BY CallInfo.RcvdDate;"
Form.RecordSource = strSQL
Me.cboCallNumber.RowSource = strSQL
Form.Requery
If Me.RecordsetClone.RecordCount = 0 Then
MsgBox "No Records Found: Try Diferent Criteria."
Form.RecordSource = "qryservicerequestentry"
Me.cboCallNumber.RowSource = "qryservicerequestentry"
Exit Sub
End If
Me.cmdSuperFilterOff.Visible = True
Exit Sub
Exit_cmdAdvancedFilter_Click:
Exit Sub
Err_AdvancedFilter_Click:
MsgBox Err.Description
Resume Exit_cmdAdvancedFilter_Click
End Sub
The first control in question is a combo box that displays the Client Name from the CallInfo form (Main Form).
Control Source: ClientID
And when expanded lists all available clients to select from the Users form (User ID is linked between the User form and CallInfo form).
Row Source: SELECT User.ClientID FROM [User];
After the re-query, this combobox will be blank, sometimes showing #Name? if you click on it.
The second control in question is a text box that shows the Client's phone number.
Control Source: PhoneNo
After the Re-query, this text box always displays #Name?
The third control in question is a text box that displays the clients office location.
Control Source: Location
What really baffles me is that THIS text box displays correctly after the re-query. I don't know why it would display the correct data when the Phone Number text box does not, seeing as they are so similar and work with similar data....
To Compare, the The form record source is normally based on:
SELECT CallInfo.CallNumber, CallInfo.ClientID, CallInfo.RcvdTech, CallInfo.RcvdDate, CallInfo.CloseDate, CallInfo.Classroom, CallInfo.Problem, CallInfo.CurrentStatus, CallInfo.Resolution, CallInfo.Severity, CallInfo.OpenStatus, CallInfo.AsgnTech, dbo_HDTechs.Email, CallInfo.FullName, CallInfo.AsgnGroup, User.Location, User.PhoneNo, CallInfo.OpenStatus
FROM dbo_HDTechs INNER JOIN ([User] INNER JOIN CallInfo ON User.ClientID = CallInfo.ClientID) ON dbo_HDTechs.TechName = CallInfo.AsgnTech
WHERE (((CallInfo.OpenStatus)=True))
ORDER BY CallInfo.RcvdDate;
Just going on what you wrote, I may take a slightly different approach (just personal preference).
I would change all of your 'IsNull' tests to also check for 'Empty'. i.e.
If IsNull(Forms![frmTips&Tricks].cboClientID) = False AND ...cliientID <> ""
Just today I had an issue relating to form references in a query WHERE clause, so I changed to:
strClientID = " (((CallInfo.ClientID) = '" & forms![frmTips&Tricks].[cboClientID] & "')) and"
Add a Debug.Print of your generated SQL, then look at it and try to run that SQL manually
Good Luck,
Wayne
Solved by designating the form in the control source like: CallInfo.ClientID
I still don't know why the Client Office displayed Correctly... Anybody have a hint? :)
TE