Very simple module failing. Error: 91, Object variable or With block variable not set - vba

This code simply pulls information from a table, and inserts it into a temporary table. From there, it updates the rows with the correct program name that correlates to the program id given, which is where it fails.
I'm not sure why this simple module won't run, I've declared the variable, as well as initialized it. The query is super simple, as well. Any help would be appreciated -- I have got to me missing something painfully obvious.
Dim year As String
Dim month As String
Dim contract As String
Dim programId As String
Dim ConsumerId As String
Dim programName As String
Dim db As Database
Dim Records As DAO.recordset
Dim Records2 As DAO.recordset
year = Forms!formAllentownMasterGeneration!cboYear
month = Forms!formAllentownMasterGeneration!cboMonth
contract = Forms!formAllentownMasterGeneration!cboContract
'Empty temporary table
strSQL = "DELETE * FROM billing_days_allentown1_temp"
DoCmd.RunSQL (strSQL)
'Gather and insert consumer information into temp table
strSQL = "INSERT INTO Billing_days_allentown1_temp (consumer_id, program_id, lname, fname, dob, transport_type, memo) SELECT consumer_info.consumer_id, consumer_info.program_id, consumer_info.lname, consumer_info.fname, consumer_info.dob, consumer_info.transport_type, consumer_info.memo FROM consumer_info WHERE contract_name = [contract]"
DoCmd.RunSQL (strSQL)
'Get ID's of all consumers in temp table so we can find program names
strSQL = "SELECT consumer_id, program_id FROM Billing_days_allentown1_temp"
Set Records = db.OpenRecordset("SELECT consumer_id, program_id FROM billing_days_allentown1_temp")
While Not Records.EOF
ConsumerId = Records!Fields(0)
programId = Records!Fields(1)
strSQL2 = "SELECT name FROM program_info where program_id = [programId]"
Set Records2 = db.OpenRecordset("SELECT name FROM program_info where program_id = [programId]")
programName = Records2!Fields(0)
strSQL2 = "UPDATE billing_days_allentown1_temp SET program_name = [ProgramName] WHERE program_id = programId and consumer_id = [consumerId]"
DoCmd.RunSQL (strSQL2)
Records.MoveNext
Wend
DoCmd.Close acForm, "formAllentownMasterGeneration"
Additionally (but admittedly a problem I haven't looked into yet), it prompts me for the contract name, despite providing it in the form. I'm sure I am referencing the variable wrong in a query; but my VBA is pretty rusty. If it's a quick fix, I'd appreciate someone pointing that out as well, otherwise it's something I'll fix on my own in due time.
Thank you.

Try this...it should clean up your SQL statements a little...and pass the variables, not [variable]
Dim year As String
Dim month As String
Dim contract As String
Dim programId As String
Dim ConsumerId As String
Dim programName As String
Dim strSQL As String
Dim strSQL2 As String
Dim db As Database
Dim Records As DAO.recordset
Dim Records2 As DAO.recordset
year = Me.cboYear '<--- Assuming you are on Forms!formAllentownMasterGeneration - you can use Me.
month = Me.cboMonth
contract = Me.cboContract
'Empty temporary table
strSQL = "DELETE * FROM billing_days_allentown1_temp"
DoCmd.RunSQL (strSQL)
'Gather and insert consumer information into temp table
strSQL = "INSERT INTO Billing_days_allentown1_temp (consumer_id, program_id, lname, fname, dob, transport_type, memo) " & _
"SELECT consumer_info.consumer_id, consumer_info.program_id, consumer_info.lname, consumer_info.fname, consumer_info.dob, consumer_info.transport_type, consumer_info.memo " & _
"FROM consumer_info " & _
"WHERE contract_name =" & contract
DoCmd.RunSQL (strSQL)
'Get ID's of all consumers in temp table so we can find program names
strSQL = "SELECT consumer_id, program_id " & _
"FROM Billing_days_allentown1_temp"
Set Records = db.OpenRecordset(strSQL)
While Not Records.EOF
ConsumerId = Records!Fields(0)
programId = Records!Fields(1)
strSQL2 = "SELECT name " & _
"FROM program_info " & _
"WHERE program_id = " & programId
Set Records2 = db.OpenRecordset(strSQL2)
ProgramName = Records2!Fields(0)
strSQL2 = "UPDATE billing_days_allentown1_temp " & _
"SET program_name = " & ProgramName & " " & _
"WHERE program_id = " & programId & " and consumer_id = " & consumerId
DoCmd.RunSQL (strSQL2)
Records.MoveNext
Wend
DoCmd.Close acForm, "formAllentownMasterGeneration"

Related

Adding new records to Access table on an update to a linked table in Access VBA SQL

I have two table one (skillsMatrix) the other table is (elementTree) with columns [mediumElement], [ID] in table skillsMatrix the mediumElement is a lookup dropdown of the mediumElements in table two. I want to write a macro to update skills matrix table to add a new record "name", "new topic","" and not duplicate any of the other records when a new mediumElement is added to elementTree.
Table: skillsMatrix
id
employee
mediumElement
completionDate
autoNumber
Dave
Walking
10/27/2020
Table: elementTree
Id
mediumElement
26
Walking
27
Running
I'd like the skillsMatrix table to look like this after running the code
id
employee
mediumElement
completionDate
autoNumber
Dave
Walking
10/27/2020
autoNumber
Dave
Running
I have tried the following to troubleshoot for building out the logic. The following prints out with RS always starting with 1 and ME starting with the proper ID for the mediumElement in element tree.
rs
1
ME
26
rs
2
ME
27
rs
3
ME
28
rs
4
ME
29
rs
5
ME
30
rs
6
ME
31
rs
7
ME
32
rs
8
ME
33
rs
9
ME
34
rs
10
ME
35
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim mediumElements As DAO.Recordset
Dim employeeTable As DAO.Recordset
Dim strSQL As String
Dim strSQLName As String
Dim strSQLintegrityCheck As String
Dim idValue As Long
Dim recordExists As Boolean
If Me.Dirty = True Then Me.Dirty = False 'Save any unsaved data
Set db = CurrentDb
strSQLName = "SELECT employeeTable.ID, employeeTable.[Employee Name] FROM employeeTable WHERE (((employeeTable.[Employee Name])=""" & Me.employeeName & """));"
Set employeeTable = db.OpenRecordset(strSQLName)
idValue = employeeTable.Fields("ID")
Debug.Print (idValue)
strSQLintegrityCheck = "Select skillsMatrix.employee, skillsMatrix.mediumElement From skillsMatrix Where skillsMatrix.employee = " & idValue & ""
Set rs = db.OpenRecordset("skillsMatrix")
strSQL = "Select elementTree.[ID], elementTree.[mediumElement] From elementTree Where ( elementTree.plantPosition = " & Me.jobPosition & ")"
'Debug.Print strSQL
Set mediumElements = db.OpenRecordset(strSQL)
Debug.Print employeeTable.Fields("ID")
If Not mediumElements.BOF And Not mediumElements.EOF Then
mediumElements.MoveFirst
rs.MoveFirst
While (Not mediumElements.EOF)
Debug.Print ("rs")
Debug.Print rs.Fields("mediumElement").Value
Debug.Print ("ME")
Debug.Print mediumElements.Fields("id")
If (rs![employee] <> employeeTable.Fields("ID") And rs![mediumElement] <> mediumElements.Fields("ID")) Then
With rs
.AddNew
![employee] = employeeTable.Fields("ID")
![mediumElement] = mediumElements.Fields("ID")
.Update
End With
End If
rs.MoveNext
mediumElements.MoveNext
Wend
End If
rs.Close
Set rs = Nothing
Set mediumElements = Nothing
Set employeeTable = Nothing
Nothing happens/wrong thing happens as the rs.Fields("mediumElement") does not give the what I would expect as the correct value. Instead of rs.[mediumElement] displaying the lookup ID of element from the elementTree table it always displays 1 through number of records in RS for rs.Fields("mediumElement"). There is an employees table and the IDs are being saved in skillsMatrix. Although I used the lookup wizard when building the connections so that could be the problem. I apologize for my poor vernacular I'm pretty new to access and SQL.
I do not want all employees to be updated with the associated new element. The code is a sub controlled by a button press and the employee to be updated is selected on that form with the control employeeName
EDIT:
On of the suggestion looking into Insert Select
the following works for adding the mediumElements to the skills matrix table,
based on whether or not they exist for a user. Is there a way to also add the employee name to the skills matrixTable with the same Insert Into?
Dim sqlString As String
Dim name As String
Dim strSQLName As String
Dim db As DAO.Database
Set db = CurrentDb
Dim employeeTable As DAO.Recordset
strSQLName = "SELECT employeeTable.ID, employeeTable.[Employee Name] FROM employeeTable WHERE (((employeeTable.[Employee Name])=""" & Me.employeeName & """));"
Set employeeTable = db.OpenRecordset(strSQLName)
idValue = employeeTable.Fields("ID")
Debug.Print (name)
sqlString = "INSERT INTO skillsMatrix (mediumElement)" _
& "SELECT elementTree.ID FROM elementTree " _
& "WHERE NOT EXISTS(SELECT * FROM skillsMatrix Where skillsMatrix.mediumElement = elementTree.ID AND skillsMatrix.employee = " & idValue & " ) "
DoCmd.RunSQL sqlString
End Sub
If employee is selected via a combobox on form, there is no need to open a recordset just to get employee ID. EmployeeID should be a hidden column of combobox and combobox should have that as its value.
idValue = Me.employeeName
If Employee ID is not available on form, a recordset is still not needed. Use DLookup.
idValue = DLookup("ID", "employeeTable", "[Employee Name]='" & Me.employeeName & "'")
Include employee field in INSERT clause and concatenate idValue to produce a calculated field in the SELECT from elementTree clause.
sqlString = "INSERT INTO skillsMatrix (employee, mediumElement) " _
& "SELECT " & idValue & " AS Emp, elementTree.ID FROM elementTree " _
& "WHERE NOT EXISTS(SELECT * FROM skillsMatrix WHERE skillsMatrix.mediumElement = elementTree.ID AND skillsMatrix.employee = " & idValue & " ) "
If employee and mediumElement are defined as a compound index in table, then don't really need the WHERE criteria since duplicate pairs will not be allowed. I don't know if this WHERE criteria slows or improves performance.
If new element ID can be captured from form, simplify code:
sqlString = "INSERT INTO skillsMatrix (employee, mediumElement) " _
& "VALUES(" & idValue & "," & idElement & ")"
Use CurrentDb.Execute instead of DoCmd.RunSQL and won't get warning popups.

Duplicate declaration in current scope error in Access

I'm writing a VBA code to submit records one by one in a recordset loop. Running into this error saying there's a "Duplicate declaration in current scope". I've run into this before when I've accidentally had duplicate variables, but this time I can't see why it's happening. I'm thinking it might have to do with the layout of the script and maybe that it's trying to repeatedly declare it? Maybe I could work around it by declaring the variables in a module? Not sure.
Private Sub submitButton_Click()
Const VmfgConnStr = "Connection string is here"
Dim qdf As QueryDef
Set qdf = CurrentDb.CreateQueryDef("")
Dim sqlString As String
sqlString = "INSERT INTO dbo.TRAINING_RECORDS (EMPLOYEE_ID, DOCUMENT_ID, REVISION, DATE_TRAINED, TRAINED_BY, STATUS, COMPETENCY, APPROVED, TYPE) " & _
"SELECT '" & rst![EMPLOYEE_ID] & "', '" & rst![DOCUMENT_ID] & "', '" & rst![LATEST_REV] & "', '" & dtTrained & "', '" & sprTrained & "', 'T', 'Not Verified', 'NO', 'Internal'"
Set objAD = CreateObject("ADSystemInfo")
Set objUser = GetObject("LDAP://" & objAD.UserName)
strDisplayName = objUser.DisplayName
Dim dtTrainedMsg As String
Dim sprTrainedMsg As String
Dim rst As Recordset
dtTrained = InputBox("Enter date trained as 'mm/dd/yyyy':", "", Format(Date, "mm/dd/yyyy"))
Debug.Print dtTrained
If StrPtr(dtTrained) = 0 Then
Exit Sub
Else
sprTrained = InputBox("Trained By:", "", strDisplayName)
Debug.Print sprTrained
If StrPtr(sprTrained) = 0 Then
Exit Sub
Else
Dim ConfirmMsg, ConfirmStyle, ConfirmTitle, ConfirmResponse
ConfirmMsg = "Continue?"
ConfirmStyle = vbYesNo
ConfirmTitle = " "
ConfirmResponse = MsgBox(ConfirmMsg, ConfirmStyle, ConfirmTitle)
If ConfirmResponse = vbYes Then
recSelect = "SELECT EMPLOYEE_ALL.EMPLOYEE_ID, TRAINING_DOCS_ALL.DOCUMENT_ID, TRAINING_DOCS_ALL.LATEST_REV " & _
"FROM TRAINING_DOCS_ALL, EMPLOYEE_ALL " & _
"WHERE EMPLOYEE_ALL.SELECTED = -1 AND TRAINING_DOCS_ALL.SELECTED = -1"
Set rst = CurrentDb.OpenRecordset(recSelect)
rst.MoveFirst
Do Until rst.EOF
Debug.Print rst![EMPLOYEE_NAME]; rst![DOCUMENT_ID]
qdf.sql = sqlString
qdf.ReturnsRecords = False
qdf.Connect = VmfgConnStr
qdf.Execute
rst.MoveNext
Loop
CurrentDb.Execute "DELETE * FROM TRAINING_RECORDS"
CurrentDb.Execute "INSERT INTO TRAINING_RECORDS (EMPLOYEE_ID, DOCUMENT_ID, REVISION, DATE_TRAINED, TRAINED_BY, STATUS) " & _
"SELECT * FROM uSysTRAINING_RECORDS " & _
"WHERE EMPLOYEE_ID = '" & EMPLOYEE_ID.Value & "'"
CurrentDb.Execute "DELETE FROM TRAINING_NEEDED " & _
"WHERE EMPLOYEE_ID LIKE '" & EMPLOYEE_ID.Value & "' AND DOCUMENT_ID LIKE '" & DOCUMENT_ID.Value & "'"
Else
End If
End If
End If
End Sub
Consider best practices in VBA and SQL generally and MS Access specifically:
VBA Tips
Use Option Explicit at the top of every module. In fact, set it as a global setting in IDE (Tools \ Options \ Require Variable Declaration) which declares line in all VBA projects going forward. This option will raise compile error if variables are used before its corresponding Dim call as many instances emerge in posted code.
Unlike SQL with its lexical order that differs from logical order (i.e., first written clause, SELECT, is usually last clause run), VBA like many other languages runs code in order of how lines are written. Therefore, Dim must come before Set or = assignment .
Related to above, place all Dim calls as top level lines before any application code. This reads better and avoids issues of variable declaration before use.
Const VmfgConnStr = "Connection string is here"
Dim rst As Recordset
Dim qdf As QueryDef
Dim recSelect As String, sqlString As String
Dim dtTrainedMsg As String, dtTrained As String
Dim sprTrainedMsg As String, sprTrained As String
Dim ConfirmMsg As String, ConfirmStyleAs String
Dim ConfirmTitle As String, ConfirmResponse As String
Dim objAd, objUser As Object
Dim strDisplayName As String
Dim Employee_ID_value As String, DOCUMENT_ID_value As String
Consistently indent your code with any blocks such as If, With, For, Do, etc. This facilitates readability and maintainability.
If StrPtr(dtTrained) = 0 Then
...
Else
...
If StrPtr(sprTrained) = 0 Then
...
Else
...
If ConfirmResponse = vbYes Then
...
Do Until rst.EOF ' REDUNDANT WITH insert-select
...
Loop
...
Else ' REDUNDANT IF EMPTY BLOCK
End If
End If
End If
SQL Tips
Use table aliases to avoid re-writing long identifiers.
Avoid looped queries and run insert-select if possible. (See below if parameterization is needed if dtTrained and sprTrained are VBA variables).
INSERT INTO dbo.TRAINING_RECORDS (EMPLOYEE_ID, DOCUMENT_ID, REVISION, DATE_TRAINED,
TRAINED_BY, STATUS, COMPETENCY, APPROVED, TYPE)
SELECT e.EMPLOYEE_ID, t.DOCUMENT_ID, t.LATEST_REV, 'dtTrained', 'sprTrained',
'T', 'Not Verified', 'NO', 'Internal'
FROM TRAINING_DOCS_ALL t, EMPLOYEE_ALL e
WHERE e.SELECTED = -1
AND e.SELECTED = -1
Be careful of cross joins as above uses due to cartesian product that can have performance issues with large tables. (e.g., 1,000 rows X 1,000 rows = 1,000,000 result rows).
If wildcards (*) are not used, don't use LIKE operator which runs a different even slower query process. Instead use equality, =.
Avoid selecting all columns with SELECT * FROM (especially in append queries). See Why is SELECT * considered harmful?.
MS Access Tips
Avoid scripting SQL strings inside VBA. Instead use stored queries with parameterization. Doing so you avoid messy concatenation and punctuation of quotes. This helps in code readability and maintainability, even efficiency as query compiler optimizes saved queries and not string queries run on the fly.
Specifically, replace CurrentDb.Execute ... with the following set up.
SQL (save as stored objects - no concatenation or line breaks)
PARAMETERS [e_id_param] TEXT;
INSERT INTO TRAINING_RECORDS (EMPLOYEE_ID, DOCUMENT_ID, REVISION,
DATE_TRAINED, TRAINED_BY, STATUS)
SELECT EMPLOYEE_ID, DOCUMENT_ID, REVISION, DATE_TRAINED, TRAINED_BY, STATUS
FROM uSysTRAINING_RECORDS
WHERE EMPLOYEE_ID = [e_id_param]
PARAMETERS [e_id_param] TEXT, [doc_id_param] TEXT;
DELETE FROM TRAINING_NEEDED
WHERE EMPLOYEE_ID = [e_id_param] AND DOCUMENT_ID = [doc_id_param]
VBA (call QueryDefs, bind param(s), and execute - no SQL shows in code)
Set qdef = CurrentDb.QueryDefs("mySavedAppendQuery")
qdef![e_id_param] = EMPLOYEE_ID.Value
qdef.Execute
Set qdef = Nothing
Set qdef = CurrentDb.QueryDefs("mySavedDeleteQuery")
qdef![e_id_param] = EMPLOYEE_ID.Value
qdef![doc_id_param] = DOCUMENT_ID.Value
qdef.Execute
Set qdef = Nothing

Access VBA: Number of query values and destination fields are not the same

I am trying to add data from an Access form to a table. When I ran sql code, I got an error message saying "number of query values and destination fields are not the same."
this is my code:
Private Sub CmdAddtoProductionDetails_Click()
Dim StrSql As String
StrSql = "Insert Into test1 (ProductName, [Lot Number], ProductionDate, Quantity, Unit, Client) Values(me! ComboProduct1, me! LotNoProduct1, me! txtDate, me! Product1Quantity! me!ComboProduct1Unit, me! ComboProduct1Client)"
CurrentDb.Execute (StrSql)
End Sub
A simpler and more direct method is to use a recordset:
Private Sub CmdAddtoProductionDetails_Click()
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("Select Top 1 * From test1")
rs.AddNew
rs!ProductName.Value = Me!ComboProduct1.Value
rs![Lot Number].Value = Me!LotNoProduct1.Value
rs!ProductionDate.Value = Me!txtDate.Value
rs!Quantity.Value = Me!Product1Quantity.Value
rs!Unit.Value = Me!ComboProduct1Unit.Value
rs!Client.Value = Me!ComboProduct1Client.Value
rs.Update
rs.Close
Set rs = Nothing
End Sub
Your SQL string will be passed to the SQL engine which does not know how to interpret me!ComboProduct1 etc. You need to insert the values of those variables into the string:
Private Sub CmdAddtoProductionDetails_Click()
Dim StrSql As String StrSql = "Insert Into test1 (ProductName, [Lot Number], ProductionDate, Quantity, Unit, Client)" & _
" Values( '" & me! ComboProduct1 & "', '" & me! LotNoProduct1 & "', #" & Format(me! txtDate, "yyyy/mm/dd") & "#, " & CStr(me! Product1Quantity) & ", '" & me!ComboProduct1Unit & "', '" & me! ComboProduct1Client & "' )"
CurrentDb.Execute (StrSql)
End Sub
Put single quotes around strings but not around numbers. Some of your fields I wasn't sure if they were numbers or strings - I made a guess.
You need to be careful with dates - check that the SQL engine is interpreting dates in yyyy/mm/dd format correctly. It will convert the string #2016/06/04# to a date automatically for you.

Mass-Update Form w/VBA & SQL - ID not pulling correctly, records not being written to temp table

Edited since original posting: I realized that I had declared the volId variable as an Integer, but it's being read as a string. Once I changed the declaration to "Dim volId As String" the SQL code appears to be getting generated properly. Now I just need help in figuring out why the records are not being inserted into the temporary table.
I am trying to create a form that will allow the user to create multiple work records without having to re-enter the date, hours, and category information. (Ex: 10 people worked the same shift at the holiday party.) The way I plan to do this is to create a temp table, write a complete record to the table for each volunteer selected, then do an INSERT query to select everything from the temp table and insert the records into the real Work_Records table. (This second portion is not done yet. I'm debugging as I go, and have gotten stuck with the first part.)
The problem is that my records do not appear to actually be getting inserted into the temp table. I'm guessing that something is wrong with my SQL code.
Thanks!
My code:
Private Sub qryAppendMassWorkRecords_Click()
On Error Resume Next
DoCmd.RunSQL "DROP TABLE Tmp"
'Declare Vars
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rstRecords As Recordset
Dim dynamicSQL As String
Dim strSQL As String
Dim strTable As String
Dim hrsWorked As Integer
Dim DateWorked As Date
Dim pgmWorked As Integer
Dim volId As String
'Set initial values
Set db = CurrentDb
Set qdf = db.QueryDefs("qryTempAppendTable")
'Create new temp table to hold values from the form
strSQL = "CREATE TABLE Tmp (VolunteerID VARCHAR(20), DateWorked DATETIME, HoursWorked INT, WorkCategory INT);"
db.Execute strSQL
'Grab the values for the static vars and assign them
For Each ctl In Me.Controls
If ctl.Properties("Name") = "DateWorked" Then
DateWorked = ctl.Value
End If
If ctl.Properties("Name") = "HoursWorked" Then
hrsWorked = ctl.Value
End If
If ctl.Properties("Name") = "WorkCategory" Then
pgmWorked = ctl.Value
End If
Next ctl
'If combo box length > 0, create an INSERT statement to add the record to the temp table
For Each ctl In Me.Controls
If ctl.ControlType = acComboBox Then
'Category is the only combo box other than the ones for volunteer names; make sure it's not getting picked up
If ctl.Properties("Name") <> "WorkCategory" Then
'Verify that the field contains a name
If Len(ctl.Value) > 0 Then
volId = ctl.Value
'Reset the dynamicSQL to the initial code & add form values
dynamicSQL = "INSERT INTO Tmp VALUES (" _
& "'" & volId & "', #" & DateWorked & "#, " & hrsWorked & ", " & pgmWorked & ");"
db.Execute dynamicSQL
End If
End If
End If
qdf.SQL = dynamicSQL
Next ctl
DoCmd.OpenTable "Tmp", acViewPreview
End Sub
Try this:
dynamicSQL = "INSERT INTO Tmp VALUES ('" _
& volId & "', #" & DateWorked & "#, " & hrsWorked & ", " & pgmWorked & ");"
It will get a good Access SQL string:
INSERT INTO Tmp VALUES ('15', #12/02/2013#, 5, 3);
In Access Database, Datetime must be quoted with sharp #, like: #mm/dd/yyyy hh:mm:ss#,
or #yyyy-mm-dd hh:mm:ss#...
#12/02/2013#
More your VolunteerID is a string, so single quote like this:
'15'
Please notify, Access can only execute one single "INSERT" instruction, not multiple INSERT's as in MySQL. If you have many records, you must do a loop using VBA.
And run it to insert into Tmp, that you have not done:
db.Execute dynamicSQL
For example, this worked for me:
Sub qryAppendMassWorkRecords_Click()
On Error Resume Next
Dim strSQL As String
Dim db
'Set initial values
Set db = CurrentDb
strSQL = "CREATE TABLE Tmp (VolunteerID VARCHAR(20), DateWorked DATETIME, HoursWorked INT, WorkCategory INT);"
db.Execute strSQL
strSQL = "INSERT INTO Tmp VALUES ('242013', #12/2/2013#, 4, 39);"
db.Execute strSQL
DoCmd.OpenTable "Tmp", acViewPreview
End Sub

How do I store the results of my select statement in a variable?

My code so far is this. The last line gives me a compile error: "expected end of statement".
Dim strSql As String
Dim groupId As String
strSql = "Select ID from RevenueGroup where description = '" & ListO.Value & "'"
groupId = CurrentProject.Connection.Execute strSql
You are looking at something kinda like this
Dim strSql As String
Dim groupId As String
strSql = "Select ID from RevenueGroup where description = '" & ListO.Value & "'"
Dim rec As Recordset
set rec= CurrentProject.Connection.Execute strSql
groupId = rec(0)
You need to set the results of the query to a recordset and then pull the first value from its results. Without all the defined variable, I cannot get this to fully compile but this should be a good template to start from.