DoCmd multiple where clauses - ms-access

I have form where user can search the database by worker ID , name/surname, job.
I want to make possible all possible variations e.g. ID+name/surname+job or ID+job, or name/surname etc.
I have done all except combinations with ID's. Searching only by ID works, but combinations don't as I do not know what is the correct syntax. I have tried many, many ways to do this, but with no result.
Here is searching only by ID:
DoCmd.OpenForm "DarbiniekiSearchResults", acFormDS
Forms!DarbiniekiSearchResults.RecordSource = "" _
& "SELECT * " _
& "FROM Darbinieks " _
& "WHERE ID_darbinieks=" & Forms!SearchDarbinieki!darbIDsearch
And here is what I am trying to do: ID+job:
DoCmd.OpenForm "DarbiniekiSearchResults", acFormDS
Forms!DarbiniekiSearchResults.RecordSource = "" _
& "SELECT * " _
& "FROM Darbinieks " _
& "WHERE ID_darbinieks= & Forms!SearchDarbinieki!darbIDsearch OR amats_darb= '" & Forms!SearchDarbinieki!darbAmatsSearch & "'"
And the error is: http://i.stack.imgur.com/NA2bi.png

Related

Update listbox ROWSOURCE when making a selection from a drop down

I have scoured around for topics relating to the idea of changing a listbox recordsource using VBA and I have created my own piece.. but it only works 1/2 way.
I have a form for tracking attendance issues for associates.. We have 2 locations, 1 in Az and 1 in Tx.. Due to recent laws that changed in Az our policies were updated.. The difference is in Az an occurrence is held for 1 year (or 365 days) and in Tx the occurrence is held for 3 months (90 days).
The basic idea is this:
If the text box for "supervisor state" = Az, the HISTORYBOX should show/calculate out 365 days of records.. else if the "supervisor state" = Tx then the HISTORYBOX should show/calculate 90 days of records.
My issue is when selecting an AZ supervisor.. it is still pulling the 90 day version of the code.. not the 365 day version.
Here is the code I have been able to create so far:
Public Sub ChangeHistory()
Dim strSQL As String
If Me.txtsupervisorstate.Value = "AZ" Then
strSQL = "SELECT OccuTable.ValueOfOccurance, " & _
" OccuTable.Short_Code_Occurance, " & _
" OccuTable.OccuranceDate, " & _
" OccuTable.Roll_Off_Date, " & _
" OccuTable.Notes, " & _
" OccuTable.AssociatedIDNumber " & _
" FROM OccuTable GROUP BY OccuTable.ValueOfOccurance, " & _
" OccuTable.Short_Code_Occurance, " & _
" OccuTable.OccuranceDate, " & _
" OccuTable.Roll_Off_Date, " & _
" OccuTable.Notes, " & _
" OccuTable.AssociatedIDNumber " & _
" WHERE (((OccuTable.OccuranceDate) Between
Date() And Date()-365) And " & _
"
((OccuTable.AssociatedIDNumber)=Forms!OccuranceTracker!txtAssociateID))
ORDER BY OccuTable.OccuranceDate DESC;"
ElseIf Me.txtsupervisorstate.Value = "TX" Then
strSQL = " SELECT OccuTable.ValueOfOccurance, " & _
" OccuTable.Short_Code_Occurance, " & _
" OccuTable.OccuranceDate, " & _
" OccuTable.Roll_Off_Date, " & _
" OccuTable.Notes, " & _
" OccuTable.AssociatedIDNumber " & _
" FROM OccuTable GROUP BY OccuTable.ValueOfOccurance, " & _
" OccuTable.Short_Code_Occurance, " & _
" OccuTable.OccuranceDate, " & _
" OccuTable.Roll_Off_Date, " & _
" OccuTable.Notes, " & _
" OccuTable.AssociatedIDNumber " & _
" WHERE (((OccuTable.OccuranceDate) Between
Date() And Date()-90) And
((OccuTable.AssociatedIDNumber)=Forms!OccuranceTracker!txtAssociateID))
ORDER BY OccuTable.OccuranceDate DESC;"
Me.listBoxPastOccurances.RowSource = strSQL
End If
Call SumOfOccu
End Sub
Here is what the form looks like:
AttendanceForm
Oh my goodness I was WAYYY overthinking this issue. My newish self to VBA was trying to find the most convoluted and confusing way to make this work.. After ALOT of research around StackOverflow I found that I can write a query and save that query for future use.. So I wrote 2 individual queries (Occurrences365 and Occurrences90).. These duplicated the original query for the listbox (when I only needed the 90 day version), which was known to work; which made creating the 365 day version super simple.
Then I was able to reduce all my other convoluted code down to this:
Public Sub ClearHistory()
If Me![txtsupervisorstate] = "AZ" Then
Me![listBoxPastOccurances].RowSource = "Occurrences365"
ElseIf Me![txtsupervisorstate] = "TX" Then
Me![listBoxPastOccurances].RowSource = "Occurrences90"
End If
Call SumOfOccu
End Sub
Public Function SumOfOccu()
If Me![txtsupervisorstate] = "AZ" Then
Me.txtSumOfOccu = DSum("valueofoccurance", "occurrences365")
ElseIf Me![txtsupervisorstate] = "TX" Then
Me.txtSumOfOccu = DSum("valueofoccurance", "occurrences90")
End If
End Function
Now I can go back and start eliminating unnecessary subs/functions, clean up the naming conventions and make it overall 'cleaner'.
For anyone interested.. the queries look like this after I wrote them as a saved query.
SELECT OccuTable.ValueOfOccurance, OccuTable.ShortCodeOccurance,
OccuTable.OccuranceDate, OccuTable.RollOffDate, OccuTable.Notes,
OccuTable.AssociatedIDNumber
FROM OccuTable
GROUP BY OccuTable.ValueOfOccurance, OccuTable.ShortCodeOccurance,
OccuTable.OccuranceDate, OccuTable.RollOffDate, OccuTable.Notes,
OccuTable.AssociatedIDNumber
HAVING (((OccuTable.OccuranceDate) Between Date() And Date()-365) AND
((OccuTable.AssociatedIDNumber)=[Forms]![OccuranceTracker]![txtAssociateID]))
ORDER BY OccuTable.OccuranceDate DESC;
again.. the only difference between the 2 is this one piece.
And Date()-365)
And Date()-90)
But everything works!
Thank you so much for the suggestions and pushing me to keep looking!

Error on INSERT INTO statement

I have the following and getting the error in INSERT INTO statement. I've done a debug.print and pasted back into SSMS and it works just fine so I'm really stumped. The syntax looks fine to me but I know sometimes going from straight SQL to VBA SQL can be tricky. I had a feeling it was the EXISTS section and I took that out and made the appropriate edits and still got the error msg. Any suggetions?
sqlstr = "INSERT INTO [database.[dbo].[table]" & _
"(" & _
"User_name" & _
",Client_Id" & _
",Client_Name" & _
",UserAccess" & _
",UserId" & _
")" & _
"SELECT " & _
"User_name = '" & UserName & "'" & _
",Client_Id = " & Me.ClientList.ItemData(ClientID) & "" & _
",Client_Name = '" & Me.ClientList.Column(1, ClientID) & "'" & _
",UserAccess = 0" & _
",UserId = " & UserId & "" & _
" WHERE NOT EXISTS (SELECT 1 FROM [database].[dbo].[table] where UserID = " & UserId & " and Client_Id = " & Me.ClientList.ItemData(ClientID) & ")"
Access SQL != T-SQL.
You either need to run this SQL string as a Pass-Through query, then it's the same as running it in SSMS.
Or translate it into Access SQL.
At the very most you must change the table names into the names of the linked tables in Access (which certainly aren't [database].[dbo].[table])
If you need more help with option 2, please post the formatted result of Debug.Print sqlstr

3011 error code access recordset vba

This is the code that I have worked over many many times, fix one error code3061, then another, now this. ANY IDEAS WHY THIS ERROR IS HAPPENING, all objects spelled correctly?
Dim strSQL As String
Dim strForms As String
strForms = [Forms]![frmEnterResRecordset]![txtPhone]
MsgBox strForms
strSQL = "SELECT tblCustomer.IDCustomer, tblCustomer.PHONE, tblCustomer.LASTNAME, " & _
"tblCustomer.FIRSTNAME, tblCustomer.NAME, tblCustomer.EMAIL " & _
"FROM tblCustomer " & _
"WHERE (((tblCustomer.PHONE) Like " & "*'" & strForms & "'*" & "));"
Check your syntax near the Like operator. The asterisks are outside the single quotes. Try replacing it as follows:
strSQL = "SELECT tblCustomer.IDCustomer, tblCustomer.PHONE, tblCustomer.LASTNAME, " & _
"tblCustomer.FIRSTNAME, tblCustomer.NAME, tblCustomer.EMAIL " & _
"FROM tblCustomer " & _
"WHERE (((tblCustomer.PHONE) Like " & "'*" & strForms & "*'" & "));"
Something I like to do when building dynamic SQL statements like this is to print it to the debug window with the following statement:
debug.print strSQL
It's easier to spot statements like:
Like *'my_entered_value'*

Run Code error in Access Macro

I am trying to make a macro in Access that will run VBA code. I trying am using the RunCode command to Run a function that will run a VBA function that I have already created but for some reason it says it can't find it and I am really confused why. I have posted a picture of the macro as well as the code below. Any help would be greatly appreciated.
Macro:
http://imgur.com/uankmL0
Code:
Function Totals()
Dim db As Database
Set db = CurrentDb
foldername = CurrentProject.Path & "\GeneralTotals"
deleteTotals = "DELETE * FROM Totals"
totalVerified = "INSERT INTO Totals([TOTAL VERIFIED FORMULARIES], [TOTAL AVAILABLE FOR IMPORT], [TOTAL SHOULD BE IMPORTED], [TOTAL RECENTLY IMPORTED]) " & _
"SELECT A.cnt, B.cnt, C.cnt, D.cnt " & _
"FROM ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM VerifiedFormularies " & _
") AS A " & _
", ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ImportMetricsIDs " & _
") as B " & _
", ( " & _
"SELECT COUNT([FORMULARY ID]) as cnt " & _
"FROM ShouldImportMetricsIDsTable " & _
"WHERE [IMPORTSTATUS]= 'Yes' " & _
") AS C " & _
", ( " & _
"SELECT COUNT([LATEST]) as cnt " & _
"FROM VerifiedFormularies " & _
"WHERE [LATEST]= 'Yes' " & _
") AS D "
db.Execute deleteTotals
db.Execute totalVerified
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel5, "Totals", foldername
MsgBox ("Totals have been exported to: " & foldername)
End Function
Your issue most likely depends on location of trigger event and code placement.
How are you triggering the RunTotals macro? With an embedded macro
using the RunMacro action or in VBA using DoCmd.RunMacro?
Where is the Function Totals() placed? It needs to be behind the form
triggering the event or in a module.
Finally, you can avoid using separate objects (RunTotals macro and embedded macro) if in your trigger event, you type into the Property sheet event line "=Totals()" Alternatively, you can simply call the function in VBA with the simple line: Totals. But location as explained in second bullet still applies.

Too few parameters, expected 1? error access

I am getting the above error whilst running this commmand:
CurrentDb.Execute "UPDATE VolunteerDetails " & _
" SET FirstName=" & Me.frst_Name_txt & _
", LastName='" & Me.lst_Name_txt & "'" & _
", PostalCode='" & Me.pst_Code_txt & "'" & _
" WHERE VolsID=" & Me.vol_ID_txt
Can anyone explain why?
Thanks!
I think your problem is in the FirstName value. It seems to be a string and so you need to put your value inside single quotes
CurrentDb.Execute "UPDATE VolunteerDetails " & _
" SET FirstName='" & Me.frst_Name_txt & "'" & _
", LastName='" & Me.lst_Name_txt & "'" & _
", PostalCode='" & Me.pst_Code_txt & "'" & _
" WHERE VolsID=" & Me.vol_ID_txt
Said that, please read about Sql Injection and Parameterized queries. Your code, as is, it is very weak and could fail simply if someone types a LastName like O'Malley (the single quote breaks your string concatenation)
As pointed by a comment above, I suppose that these variables are not TextBoxes but just string variables. If these are TextBoxes then, the value to set the field to comes from the Text property of the TextBox. Something like
" SET FirstName='" & Me.frst_Name_txt.Text & "'"