Run Code error in Access Macro - ms-access

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.

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'*

DoCmd multiple where clauses

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

Inserting string variable into sql string in vb.net

I am having a hard time inserting WONum into my sql string.
I have tried using ' and double '' around WONum. Someone also suggested # and [] around it, but nothing is working thus far.
I keep getting the following error: Incorrect syntax near '1577'
WONum value is actually WO-1577 during run time, but when DA.fill is executed I get that error. I starting to think that the dash is doing something in sql that I'm not aware of. Any help would help, because I have to do several more similar functions in my application.
Public Function GetTechTimes(ByVal WONum As String)
Dim strSQL As String = "Select customer_name, workorder_work_to_be_performed, workorder_work_performed, workorder_notes, workorder_warranty_work, workorder_open_date, workorder_status,workorder_completion_date, wo_tech_name, wo_tech_time, wo_parts_description from Customers, workorders, WorkOrder_Technicians, WorkOrder_Parts Where(customer_id = workorder_customer And wo_tech_wo_id = workorder_id And wo_parts_wo_id = workorder_id And workorder_number = " & WONum & ""
Dim DA As New SqlDataAdapter(strSQL, Conn)
Dim DS As New DataSet
DA.Fill(DS, "TechTimes")
Return DS
End Function
Use Sql-Parameters! That will avoid conversion or other issues and - more important - prevents SQL-Injection attacks.
Public Function GetTechTimes(ByVal WONum As String) As DataSet
Dim strSQL As String = "SELECT customer_name, " & Environment.NewLine & _
"workorder_work_to_be_performed," & Environment.NewLine & _
"workorder_work_performed, " & Environment.NewLine & _
"workorder_notes, " & Environment.NewLine & _
"workorder_warranty_work, " & Environment.NewLine & _
"workorder_open_date, " & Environment.NewLine & _
"workorder_status, " & Environment.NewLine & _
"workorder_completion_date," & Environment.NewLine & _
"wo_tech_name, " & Environment.NewLine & _
"wo_tech_time, " & Environment.NewLine & _
"wo_parts_description" & Environment.NewLine & _
"FROM(customers," & Environment.NewLine & _
" workorders," & Environment.NewLine & _
" workorder_technicians," & Environment.NewLine & _
" workorder_parts)" & Environment.NewLine & _
"WHERE customer_id = workorder_customer " & Environment.NewLine & _
"AND wo_tech_wo_id = workorder_id " & Environment.NewLine & _
"AND wo_parts_wo_id = workorder_id " & Environment.NewLine & _
"AND workorder_number = #workorder_number "
Using con = New SqlConnection(YourConnectionString)
Using da = New SqlDataAdapter(strSQL, con)
da.SelectCommand.Parameters.AddWithValue("#workorder_number", WONum)
Dim DS As New DataSet
da.Fill(DS)
Return DS
End Using
End Using
End Function
Note that i've also used Using-statements to ensure that all gets diposed even in case of an exception.
Bye the way, the reason for your exception: you had an opening brace here: Where(customer_id which was never closed.
As long as workorder_number is a string then putting single quote ' around the WONum is all you need.
You won't need # or square brackets.
If it's not working with the single quote then ensure you've identified/isolated your problem correctly. Remove the And workorder_number = " & WONum & "" from the end of your sql and see if it works without that. If not, then your problem isn't in the WONum, it's earlier in the string.