Edit: The issue was On Error Resume Next suppressing the errors in OpenRecordset, leaving the Variant set to Nothing. OpenRecordset failed due to misspelled column names, and specifying Type when Type is determined by default by proxy of being a linked table.
Solution: Comment out/remove On Error Resume Next to raise errors. Correct spelling errors in column names. Do not specify type (leave position blank) when Querying from Linked table (Type is automatically Dynaset for querys from linked tables.
In a particular section of code, I am trying to display the number of records in a recordset (mostly for debugging purposes). I stumbled across what I believe to be a unique error. The Code is as follows:
specsVariableTempTableName = "specs_variable_" & CStr(Me.OpFormOpRecordID) & "_temp"
specItemsQuery = "SELECT [Item], [Document #], [Item Description], [SubItems], [Attribute], [Spec Characteristics] FROM [tbl_forms] WHERE [Document #] = '" & Me![Form #] & "' AND [Part #] = '" & Me![Part Number] & "';"
Set db_source = CurrentDb
If IsNull(DLookup("Name", "MSysObjects", "Name='" & specsVariableTempTableName & "' And Type In (1,4,6)")) Then
'Check for existing temporary spec table
'Create one if not
MsgBox ("No temporary table " & specsVariableTempTableName)
Set specItemsRecordSet = db_source.OpenRecordset(specItemsQuery, , dbFailOnError).Clone
MsgBox (specItemsRecordSet.RecordCount & " Records")
MsgBox ("What the f***")
If Not (specItemsRecordSet.EOF And specItemsRecordSet.BOF) Then
'If the result set is not empty, go to first entry
specItemsRecordSet.MoveFirst
With specItemsRecordSet
MsgBox (.RecordCount)
End With
Else
MsgBox ("No Specs found for given part number and document number")
End If
db_source.Execute "SELECT [Document #], [Part #], [ParentItem], [SubItem], [Nominal], [LSL], [USL], [UOM] INTO " & specsVariableTempTableName & " FROM [Specs_Variable] WHERE (([Specs_Variable]![Document #] = '" & Me![Form #] & "') AND ([Specs_Variable]![Part #] = '" & Me![Part Number] & "'));", dbFailOnError
End If
The line in-question is MsgBox(specItemsRecordSet.RecordCount & " Records"). The MsgBox lines before and after this line display a MsgBox and I have to click OK to close it. However, this particular line displays no MsgBox, the code does not pause, it simply continues to the next line as if the code weren't there at all.
I have tried to rename the tables in the query, I have tried .MoveLast before invoking .RecordCount. Even the MsgBox in the WITH block does not show. I would expect that if the query returned no results that I would get a 0, Null, or an Error when trying to show in MsgBox but that the MsgBox would still show and require user action to continue.
Related
I'm totally stumped at this one.. Skip to bottom to read problem
Here's my listbox (DocumentList) that takes the fields from the 'Documents' Table:
Document Name Status Notes Consultation Notes
Doc A Started Document Started Aim to process on 05/05/16
Doc B Processing Document Processing Aim to complete on 05/05/16
Doc C Complete Complete on 01/01/16 N/A
I have the onclick event set so that when you select a row from the listbox, it assigns each field to a text box/Combobox.
textboxes/Combobox names:
txtDocument
StatusCombo
txtNotes
txtConNotes
code for each one in 'DocumentList' click event:
Private Sub DocumentList_Click()
txtDocument = DocumentList.Column(0)
StatusCombo = DocumentList.Column(1)
txtNotes = DocumentList.Column(2)
txtConNotes = DocumentList.Column(3)
After the data is assigned to them from the listbox, you can edit it. I have an update button, which when pressed will replace everything in the database with everything in the textboxes/Combobox. The listbox is then re-queried and displays the updated data.
Heres the code for my update button:
Private Sub UpdateButton_Click()
CurrentDb.Execute "UPDATE [Documents] " & _
"SET [Document Name] = '" & Me.txtDocument & "'" & _
", [Status] = '" & StatusCombo.Value & "'" & _
", [Notes] = '" & Me.txtNotes & "'" & _
", [Consultation Notes] = '" & Me.txtConNotes & "'" & _
"WHERE [Document Name] = '" & DocumentList.Column(0) & "'" & _
"AND [Status] = '" & DocumentList.Column(1) & "'" & _
"AND [Notes] = '" & DocumentList.Column(2) & "'" & _
"AND [Consultation Notes] = '" & DocumentList.Column(3) & "'"
DocumentList.Requery
End Sub
My problem is the code only works on 2 out of 3 of the documents. All aspects of the code work, but only on some of the documents. This doesn't make any sense to me. At first I thought it may be a spelling error, but even if it was, none of the documents should get updated.. But some of them do, 1 doesn't..
Any ideas why this code updates some documents, but doesn't update others?
Nothing is updated when [Documents].[Consultation Notes] is Null, because the WHERE clause targets an empty string instead ... "'" & DocumentList.Column(3) & "'" ... so no matching row is found.
The task would be simpler if you add an autonumber primary key, ID, to the [Documents] table. Then include ID in the list box Row Source, and use that value in the WHERE clause to target the row you want to update. (The ID column doesn't have to be visible in the list box; you can set its column width property to zero.)
Then your WHERE clause can be much simpler: just target the record whose ID matches the ID column value of the selected list box row. That strategy would also avoid the complication of "Null is never equal to anything, not even another Null".
Finally, consider a parameter query for the UPDATE instead of concatenating values into a string variable.
I am trying to display error message in MS Access which will get the error from one table.
There is a table, having only one column which is having error records. I need to display all the records from table in message box of ms access.
I know how to get the message box but unable to find how to fetch records in the msg box
MsgBox "Errors are :" & vbCr & _
"E.g. 000123", vbCritical + vbOKOnly
How can i get the values from table?
Add this sub in your form or a stand alone module :
Public Sub DisplayErrors()
Dim RS As Recordset
Dim strErrors as string
Set RS = CurrentDb.OpenRecordset("SELECT * FROM MyErrorTable")
If Not RS.BOF Then
While Not RS.EOF
strErrors = strErrors & RS!MyErrorField & vbCrLf & vbCrLf
RS.MoveNext
Wend
End If
RS.Close
Set RS = Nothing
MsgBox "Errors are : " & vbCrLf & strErrors , vbCritical + vbOKOnly
End Sub
Replace MyErrorTable and MyErrorField with the name of your table and it's unique field containing the errors.
Then call your sub from anywhere with :
DisplayErrors
So I have been scratching my head for awhile on this issue and although it seems simple in theory I am having a tough time implementing it in VBA.
Some background on the project will be needed to understand what i am trying to do
So our database/application is meant to keep track of how we test a version of software, what the results are, and if the tests were done properly. we have a specific set of scripts that we use from version to version.
In the database we have a table that list these scripts without assigning them to a specific version of software.
then we have a form where you select the version of software you are running against.
here is the problem i am encountering
when you have selected a software version I want to have a button that you click and it takes all the associated test scripts copies them and assigns the selected software version IF THIS HASNT BEEN DONE YET. this will allow you to make notes for the specific script that can differ from version to version.
I am currently trying to do this with a union query and have experimented with using the append query but haven had any luck, with the code snippet that i am putting below the results i get when i click the button to execute the assigning of the software version it alerts the proper "Test Script", PROC_CHECK_ID and "Software Version" but then i get a strange prompt that sais "Enter Paramater Value" and it sais the "Test Script Name" with a text field, this goes into an infite loop where i can just keep entering values in the text field.
Here is my code
Dim rs1 As DAO.Recordset
Dim unionquery As String
Dim CURRENT_SOFTWARE_VERSION As String
CURRENT_SOFTWARE_VERSION = Me.Parent.[Software Version].Value
unionquery = "select [Test Script] , [PROC_CHECK_ID], [Software Version] from (FORMAL_CERT_PROCEDURE_TEST_SCRIPTS inner join FORMAL_CERT_PROCEDURE_CHECK on FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID = FORMAL_CERT_PROCEDURE_CHECK.TEST_CASE_ID) inner join FORMAL_CERT_SOFTWARE_VERSION on FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID = FORMAL_CERT_SOFTWARE_VERSION.TEST_CASE_ID where PROC_CHECK_ID=" & Me.PROC_CHECK_ID & " AND [Software Version]=""" & CURRENT_SOFTWARE_VERSION & """ "
' Debug.Print unionquery
Set rs1 = CurrentDb.OpenRecordset(unionquery, dbOpenForwardOnly)
If Not (rs1.EOF And rs1.BOF) Then
Do Until rs1.EOF = True
' MsgBox " " & rs1![Test Script] & ", " & rs1![PROC_CHECK_ID] & ", " & rs1![Software Version] & " "
INSERT_INTO_TEST_SCRIPTS = "insert into FORMAL_CERT_PROCEDURE_TEST_SCRIPTS([Test Script], [PROC_CHECK_ID_FK], [Software_Version], [TEST_CASE_ID]) values(" & rs1![Test Script] & ", " & rs1!PROC_CHECK_ID & ", " & rs1![Software Version].Value & ", " & Me.TEST_CASE_ID & ")"
' APPEND QUERY THAT THROWS INTO AN INFINITE LOOP *NEEDS WORK* INSERT_INTO_TEST_SCRIPTS = "INSERT INTO FORMAL_CERT_PROCEDURE_TEST_SCRIPTS([Test Script], [PROC_CHECK_ID_FK], [Software_Version], [TEST_CASE_ID]) SELECT FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.[Test Script], " & rs1!PROC_CHECK_ID & ", " & rs1![Software Version].Value & ", FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID FROM FORMAL_CERT_PROCEDURE_TEST_SCRIPTS WHERE FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID = " & Me.TEST_CASE_ID & " "
DoCmd.SetWarnings False
DoCmd.RunSQL INSERT_INTO_TEST_SCRIPTS
DoCmd.SetWarnings True
rs1.MoveNext
Loop
End If
I appreciate any help and am willing to completely rework this mechanic, i am probably over complicating this : /
thanks!
Your first SELECT query (unionquery) has quotes around the value for [Software Version], indicating that it is a text field. However, your subsequent INSERT query (INSERT_INTO_TEST_SCRIPTS) omits the quotes. Therefore, the INSERT query is treating the value you are trying to insert as the name of some other field, and since no other field exists with that name you are getting the parameter prompt.
Your code might be a bit cleaner (and more reliable) if you did a Recordset insert instead of "gluing together" an INSERT statement. That approach would look something like this:
Dim rs2 As DAO.Recordset
Set rs2 = CurrentDb.OpenRecordset( _
"SELECT * FROM FORMAL_CERT_PROCEDURE_TEST_SCRIPTS", _
dbOpenDynaset)
rs2.AddNew
rs2![Test Script] = rs1![Test Script]
rs2![PROC_CHECK_ID_FK] = rs1!PROC_CHECK_ID
rs2![Software_Version] = rs1![Software Version]
rs2![TEST_CASE_ID] = Me.TEST_CASE_ID
rs2.Update
rs2.Close
Set rs2 = Nothing
I have a data entry form (Access 2007) which is designed to find out if the captured animal already has an existing WHno. Unfortunately, the data is messy and these is not a single unique identifier so several tests must be performed to narrow the search.
The animal could have 1 to 10 different pieces of information which will help identify the animal’s existence in the database. (The script only tests for about half of them thus far) I was thinking the best way to do this would to be to “build” a DCount and/or SQL statement based on which fields the user selects. I hope test to see if a particular text field box (unbound) has been filled out, and if yes, concatenate that section of code to the DCount/SQL statement, then move on to the next text field box to test.
Once the statement has been completely built, I want to test to see how many records have been counted/selected. If one record has been selected, I want to display the results in FormA. If 2 or more records are found, I want to display the records in a multi-listing form (FormB) from which the user can select the correct animal based on additional information not tested but displayed in FormB. If zero records are found, I want to create a new record with the data entered into the form updated into the table.
The hurdle I am struggling with now is building the DCount statements. I keep getting syntax errors . I do not know how to put this together piecemeal when the function bombs out because the syntax is incomplete (which it will be until I finish “building” it.)
I know the data is a mess. The scene out in the field is chaotic, different people gather different kinds of information, and not all the data that should be entered on the paper forms get filled out completely - if at all. The data gathering procedures are unlikely to change anytime soon.
Ideas? A different but easier approach idea is also welcome. New to this and not sure of all my programming options.
Also, how long can this statement be before it bombs out?
Code so far:
Private Sub GenerateWHno_Click()
Dim rs As DAO.Recordset
If IsNull(Forms!F_HotelEntry!txtSpecies) Or (Forms!F_HotelEntry!txtSpecies) = "" Then
MsgBox "Species is a required field. Please enter a species"
Exit Sub
End If
MsgBox txtSpecies
' Each line of code below indicates a data entry field(s) that needs testing and appended to SpeciesCount if "true". The first line is unchanging and is declared upfront.
'SpeciesCount = DCount("[Species]", "AnimalInfo", "(nz([Status])= '' OR [Status] = 'Alive' OR [Status] = 'Unknown') AND ([Species]= '" & txtSpecies & "')" _
' & "AND (((nz([L_ET_Color1])= '" & Nz(txtL_ET_Color1) & "' AND nz([L_ET_No1])= '" & nz(txtL_ET_No1) & "')" _
' & "AND (((nz([R_ET_Color1])= '" & Nz(txtR_ET_Color1) & "' AND nz([R_ET_No1])= '" & nz(txtR_ET_No1) & "')" _
' & "AND nz([L_ET_No2])= '" & nz(txtL_ET_No2) & "')" _
' & "AND nz([R_ET_No2])= '" & nz(txtR_ET_No2) & "')" _
' & "")
'If txtL_ET_Color Is Not Null Or txtL_ET_No Is Not Null Then
'LET1 = & "AND (((nz([L_ET_Color1])= '" & Nz(txtL_ET_Color1) & "' AND nz([L_ET_No1])= '" & nz(txtL_ET_No1) & "')" _
'Species Count = SpeciesCount & LET1
'End If
'If txtR_ET_Color Is Not Null Or txtR_ET_No Is Not Null Then
'RET1 = & "AND (((nz([R_ET_Color1])= '" & Nz(txtR_ET_Color1) & "' AND nz([R_ET_No1])= '" & nz(txtR_ET_No1) & "')" _
'Species Count = SpeciesCount & RET1
'End If
'If txtL_ET_No2 Is Not Null Then
'LET2 = AND nz([L_ET_No2])= '" & nz(txtL_ET_No2) & "')" _
'Species Count = SpeciesCount & LET2
'End If
'If txtR_ET_No2 Is Not Null Then
'RET2 = AND nz([R_ET_No2])= '" & nz(txtR_ET_No2) & "')" _
'Species Count = SpeciesCount & RET2
'End If
'There are about 4 more options/fields to add to the script but you get the idea.
'Thus: If user selected Species, and filled out L_ET_Color1 and/or L_ET_No1, the final concatenation (DCount statement)would look like this:
SpeciesCount = DCount("[Species]", "AnimalInfo", "([Status]= 'Alive' OR [Status] = 'Unknown' OR nz([Status]) = '') AND [Species]= '" & txtSpecies & "' AND (nz([L_ET_Color1])= '" & Nz(txtL_ET_Color1) & "' AND nz([L_ET_No1])= '" & Nz(txtL_ET_No1) & "')")
If SpeciesCount > 1 Then
MsgBox SpeciesCount & " Greater than 1. Please select correct animal"
'Create SQL statement that mimics DCount statement and display all fields from AnimalInfo table as multilisting to select from
ElseIf SpeciesCount = 0 Then
MsgBox "You need a new WHno"
WHno = Nz(DMax("WHno", "AnimalInfo")) + 1
MsgBox WHno
Set rs = CurrentDb.OpenRecordset("AnimalInfo")
rs.AddNew
rs!WHno = WHno
rs!Species = txtSpecies
rs!L_ET_Color1 = txtL_ET_Color1
rs!L_ET_No1 = txtL_ET_No1
rs.Update
rs.Close
Else
'Create SQL statement that mimics DCount statement and display all fields from AnimalInfo table as single listing in a form.
MsgBox "You're WHno is " & WHno & " Is this the correct WHno?"
End If
Forms!F_HotelEntry!txtSpecies = ""
Forms!F_HotelEntry!txtL_ET_Color1 = ""
Forms!F_HotelEntry!txtL_ET_No1 = ""
End Sub
I would suggest to first compose the condition into a string variable. There you can print its content via Debug.Print and see what the problem might be.
If you cannot spot the problem via inspection alone, paste the generated string to the Sql view of a proper query and see if Access gives you helpful information on switching to design view.
After I edit information and change the information and click update, it gives me a error. I tried the parenthesis brackets no luck.
Too few parameters Expected 1. Run time error '3061'
Private Sub cmdUpdate_Click()
Dim strSql As String
strSql = "UPDATE PlantTransaction " & _
"SET TransactionID=" & Me.txtTranID & _
",[Plant Number]='" & Me.txtPlantNo & "'" & _
",TransactionDate=#" & Me.txtTransDate & "#" & _
",Opening_Hours='" & Me.txtOpeningHRS & "'" & _
",Closing_Hours='" & Me.CloseHrs & "'" & _
",Fuel='" & Me.txtFuel & "'" & _
",[Fuel Cons Fuel/Hours]='" & Me.txtFuelConsFuelHr & "'" & _
",[Hour Meter Replaced]='" & Me.txtHrMtrRep & "'" & _
",Comments='" & Me.txtComments & "'" & _
",[Take on Hour]='" & Me.txtTOH & "'" & _
" WHERE TransactionID=" & Me.PlantTransactionQuery.Form.Recordset.Fields("Tr ansactionID")
Debug.Print strSql ' <- prints to Immediate window
CurrentDb.Execute strSql, dbFailOnError
cmdClear_Click
Me.PlantTransactionQuery.Form.Requery
End Sub
You were smart to include this line in your code:
Debug.Print strSql ' <- prints to Immediate window
Now when you get the missing parameter message, go to the Immediate window (you can use Ctrl+g to go there) and copy the SQL statement.
Then create a new Access query in the query designer, switch to SQL View, and paste in the text you copied. When you attempt to run that query, Access will present a parameter input box which includes the name of whatever it thinks is the parameter.
Compare that parameter name with the field names in your data source. Often this situation occurs because the query includes a misspelled field name. Another possibility with an UPDATE is that one of the values you're trying to update is unquoted text. Regardless of the cause, the parameter name from that input box should help you track it down. Show us the actual text from that UPDATE statement if you need further help.
Any time that you "glue together" a long SQL statement with lots of user input you face the challenges of
correctly delimiting strings and dates,
escaping delimiters within such fields (usually quotes inside a text field), and
getting all of the required commas in the right places
You can avoid those annoyances by using a Recordset to perform the update:
Dim rst As DAO.RecordSet
Set rst = CurrentDb.OpenRecordset("PlantTransaction", dbOpenDynaset)
rst.FindFirst "TransactionID=" & Me.PlantTransactionQuery.Form.Recordset.Fields("Tr ansactionID")
If Not rst.NoMatch Then
rst.Edit
rst!TransactionID = Me.txtTranID
rst![Plant Number] = Me.txtPlantNo
rst!TransactionDate = Me.txtTransDate
rst!Opening_Hours = Me.txtOpeningHRS
rst!Closing_Hours = Me.CloseHrs
rst!Fuel = Me.txtFuel
rst![Fuel Cons Fuel/Hours] = Me.txtFuelConsFuelHr
rst![Hour Meter Replaced] = Me.txtHrMtrRep
rst!Comments = Me.txtComments
rst![Take on Hour] = Me.txtTOH
rst.Update
End If
rst.Close
Set rst = Nothing