Suppress Error Messages in Access - ms-access

I have an access form that runs a query. However it runs a query using vba code and sometimes it searches the table for text fields and sometimes for number fields depending on the field they choose on a combo box in the form.
I have left a note that if they wish to search for a text field they must enter double quotes or the code will not work. However, if the user does not follow these directions they will get a popup that exlains the coding issue with the options debug and end. I do not want them to see this message.
Is there a way to suppress this error message and write my own?
Edit:
Dim dbsCurrent As Database
Dim qryTest As QueryDef
varWhere = "WHERE InclusiveParent." & Combo0.Value & "=" & Text2
varWhere = "select Location, IcmService, IcmScript, ThresholdVariable, PbxVdn, Domestic, FirstSecondLook, DNIS, Tollfree, Outdial, Description, Carrier, DefaultTollfree, BlockedRoute, Variable3, Variable4, Variable5, Variable9, ValueScrVdn, Cvp from InclusiveParent " & varWhere
'Filter frmCustomers based on search criteria
'Dim dbsCurrent As Database
'Dim qryTest As QueryDef
Set dbsCurrent = CurrentDb
Set qryTest = dbsCurrent.QueryDefs("Broaden")
qryTest.SQL = varWhere
'Close frmSearch
DoCmd.Close acForm, "SearchDependents"
InclusiveParent is a query that I'm requery-ing and Broaden is the requery. SearchDependents is the name of the Form. Combo0 is a combo box that lets them select which field to choose to filter. And Text2 is the text field that they enter the filter criteria in. However, not all fields are numbers, so when they choose to filter by a text field they must enter double quotes or the code fails.

Try this and remove the note to require quotation marks:
varWhere = "WHERE InclusiveParent." & Combo0.Value & "="
If IsNumeric(Text2.Value) Then
varWhere = varWhere & Text2.Value
Else
varWhere = varWhere & """" & Text2.Value & """"
End If

Since Combo0.Value is the name of a field in InclusiveParent query, check the data type of that field. You can use that information to determine whether or not you need to wrap Text2.Value in quotes. By knowing the field's data type, you can also validate Text2.Value ... make sure it is a valid number when Combo0.Value is a number field. This will also allow you to ensure sure the value is quoted when the user enters only digits for Text2.Value but Combo0.Value is a text field.
Select Case dbsCurrent.QueryDefs("InclusiveParent").Fields(Me.Combo0.Value).Type
Case dbBigInt, dbByte, dbCurrency, dbDecimal, dbDouble, _
dbFloat, dbInteger, dbLong, dbSingle
If Not IsNumeric(Me.Text2.Value) Then
'* warn user and request a valid number *'
Else
'* build WHERE clause without quotes around Text2.Value *'
End If
Case dbChar, dbMemo, dbText
'* build WHERE clause with quotes around Text2.Value *'
Case Else
'* decide what you want for field which is neither text nor numeric *'
End Select

Related

How to use a variable string to reference an existing object name on a form

I have an access 2007 form with 18 textbox controls in two columns. They are to add colors and color codes to a vendor table when entering a new style.
Column one's controls are named Color1, Color2, etc, and column two's controls are named Code1, Code2, etc.
The code below goes through the textbox controls on the form and gets the control's name and value fine.
I do realize I'll need to put another if/then type statement to only perform the actions if the control selected by the case statement has a name beginning with "color". I'll add that later.
If you see the sql statement, I'm trying to insert a new color/code combination by calling up the control with the name beginning with "code" and ending with the number associated with the "color" textbox currently being evaluated in the case select.
TL;DR, when textbox "color1" is being evaluated, I want the value of what is in "code1" to be a part of the sql statement as well. The number at the end is the link between the two.
I'm sure I'm probably using an incorrect reference for ctrlcode or something like that, but if someone knows what I'm trying to do and could help me get this working, I'd appreciate it.
Dim sql As String, ctrlcode As Control 'Also tried as Object
For Each ctl In Me.Controls
Select Case ctl.ControlType
Case acTextBox 'Only searching textboxes
'Debug.Print ctl.Name, ctl.Value
If Not IsNull(ctl.Value) Then
Debug.Print ctl.Name, ctl.Value, Right(ctl.Name, 1)
**Next line fails Runtime error 424, object required**
Set ctrlcode = frm.Controls("code" & Right(ctl.Name, 1))
Debug.Print ctrlcode.Value, "ctrlcode value"
sql = "INSERT INTO tblVendorColors (Stylecode, color, colorcode, coloravail)" _
& " VALUES (Styletext, '" & ctl.Value & "', '" & ctrlcode.value & "', true)"
Debug.Print sql
End If
Case Else
' pass
End Select
Next
Use For i = 1 To 9 to loop through your text box pairs. Then you can reference the text box values as Me.Controls("Color" & i).Value and Me.Controls("Code" & i).Value
Instead of building and executing an INSERT, you can add a row to a recordset and store the values there.
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim i As Long
Set db = CurrentDb
Set rs = db.OpenRecordset("tblVendorColors", dbAppendOnly)
With rs
For i = 1 To 9
If Not IsNull(Me.Controls("Color" & i).Value) Then
.AddNew
!Stylecode.Value = Me!Styletext.Value
!Color.Value = Me.Controls("Color" & i).Value
!colorcode.Value = Me.Controls("Code" & i).Value
!coloravail.Value = True
.Update
End If
Next
.Close
End With
**Next line fails Runtime error 424, object required**
Set ctrlcode = frm.Controls("code" & Right(ctl.Name, 1))
Instead of frm., use Me..
You should put Option Explicit at the start of all modules, and set the Require Variable Declaration option in the VBA Editor. This forces you to Dim all variables and find such errors already at compile time.
In addition, if Styletext is a control, you need to treat it as ctl and ctrlcode when building your SQL string.
" VALUES ('" & Me.Styletext & "', '" & ctl.Value ...

filter continuous form using textbox

I need to let users filter a continuous form using values the user enters into a textbox. And the continuous form is also nested within a couple levels of navigation subforms. This sounds easy enough, but all the examples I find on the web use macros instead of vba.
I set up the structure and wrote an AfterUpdate procedure for a textbox txtFilter as follows:
Private Sub txtFilter_AfterUpdate()
Dim filterval As String
filterval = txtFilter.Value
With Forms!Main!NavigationSubform.Form!NavigationSubform.Form
.Filter = "LastName Like " & filterval
.FilterOn = True
End With
End Sub
I have played with different syntax, but none of it seems to work properly. Here is a link to download the relevant parts of the database from a file sharing site: http://jmp.sh/v/HGctZ4Ru74vDAjzN43Wq
Can anyone show me how to alter this so that users can use the textbox to filter the continuous form?
I got it to work using this: .Filter = "LastName Like """ & filterval & """"
Need those annoying String Identifiers even for strings sometimes.
Okay, To get the form to open with no records and then pull up just the records you (or the user) specifies is easiest with a bit of re-work.
(I'd recommend you working with a copy and not your original)
1:On your Continuous Form, remove the Recordsource; we're going to use Late Binding (Kinda)
2:Then delete the code under the txtFilter box, then delete the box itself.
3:Add a comboBox with something like this as the recordsource:
SELECT DISTINCT myTable.LastName FROM myTable ORDER BY myTable.LastName; (This will get you a unique list of last names so knowing how to spell the name will not be necessary, plus it assures at least one match)
4:In the After Update event of that combobox, add code like this:
Dim strSource As String
strSource = "SELECT mt.IntakeNumber, mt.ClientNumber, " & _
"mt.LastName, mt.FirstName, mt.ConsultationDate " & _
" FROM myTable mt " & _
"WHERE (mt.LastName)= '" & Me.cboFilter.Value & "'"
Me.RecordSource = strSource
Me.Requery
Obviously you'll need to change the table and field names as necessary, but hopefully you get the idea.
Option Compare Database
Option Explicit '<- always include this!!!!!
Private Sub txtFilter_AfterUpdate()
Dim strFilter As String
' only set Filter when text box contains something
' to search for ==> don't filter Null, empty string,
' or spaces
If Len(Trim(Me.txtFilter.Value & vbNullString)) > 0 Then
strFilter = "LastName Like '*" & _
Replace(Me.txtFilter.Value, "'", "''") & _
"*'"
' that Replace() prevents the procedure from breaking
' when the user enters a name with an apostrophe
' into the text box (O'Malley)
Debug.Print strFilter ' see what we built, Ctrl+g
Me.Filter = strFilter
Me.FilterOn = True
Else
' what should happen here?
' maybe just switch off the filter ...
Me.FilterOn = False
End If
End Sub

Concatenating Null values in DCount query that compare to corresponding concatenated table fields

Using Access 2007.
I have to compare several data entry fields with their corresponding tables fields. If the fields match, do not add a new record. If not, add a new record with the values.
AnimalInfo Table fields
WHno (Wildlife Health Number)
Species
LETClr1 (Left Ear Tag Color 1)
LETNo1 (Left Ear Tag Number 1)
LETClr2 (Left Ear Tag Color 2)
LETNo2 (Left Ear Tag Number 2)
RETClr1 (Right Ear Tag Color 1)
RETNo1 (Right Ear Tag Number 1)
RETClr2 (Right Ear Tag Color 2)
RETNo2 (Right Ear Tag Number 2)
Form F_HotelForm unbound fields
txtSpecies
txtLETClr1
txtLETNo1
txtLETClr2
txtLETNo2
txtRETClr1
txtRETNo1
txtRETClr2
txtRETNo2
I am trying to create a DCount to check and see if there are any matching records. The animal's uniqueness is determined by its species and ear tag information. It can have one ear tag number and color, or four. (Some of the older data has none but I can't do anything about that! In those cases, a new record, i.e. new Wildlife Health Number will be generated)
This is what I want to accomplish with this form:
If there are no matching fields (DCount = 0) add a new record and update fields from the form into table.
If there is 1 matching record, then the animal's wildlife health number is displayed (in a new form eventually)
If there are multiple records, then these are displayed in another form and the user needs to pick the correct animal.
LETClr1 and LETNo1 are paired.
LETClr2 and LETNo2 are paired.
RETClr1 and RETNo1 are paired.
RETClr2 and RETNo2 are paired.
Any and all of these fields could have values or not. Left ear tag numbers and colors could have been entered as either LETClr1 or LETClr2 so I have to compare both LETClr1 and LETClr2 with the txtLETClr1 data entry. (This holds true for all paired fields)
Below is a sample of the script so far. It is very rudimentary as I am very new to this and am just trying to see what works.
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
SpeciesCount = DCount("[Species]", "AnimalInfo", "[Species]= '" & txtSpecies & "'AND [L_ET_Color1]='" & txtL_ET_Color1 & "' AND [L_ET_No1]='" & txtL_ET_No1 & "'")
If SpeciesCount > 1 Then
MsgBox SpeciesCount & " Greater than 1"
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!R_ET_Color2 = txtR_ET_Color2
rs.Update
rs.Close
Else
End If
Forms!F_HotelEntry!txtSpecies = ""
Forms!F_HotelEntry!txtL_ET_Color1 = ""
Forms!F_HotelEntry!txtL_ET_No1 = ""
End Sub
So the problem is that I cannot concatenate NULL fields. The DCount only works if there is Non Null data in the form/table.
Any ideas as to how I can work around this?
Many thanks.
My comments are getting garbled so I am putting below original posting.
I copied the suggested code into module and rewrote query a couple of different way but still got error message: Run-time error 424. Object required
SpeciesCount = DCount("[Species]", "AnimalInfo", "[Species] = txtSpecies AND (is_null([L_ET_Color1],"""") = is_null(txtL_ET_Color1,""""))")
SpeciesCount = DCount("[Species]", "AnimalInfo", "[Species] = '" & txtSpecies & "'AND is_null([L_ET_Color1],"") ='" & is_null(txtL_ET_Color1, "") & "' AND [L_ET_No1]='" & txtL_ET_No1 & "'")
I have been tinkering with this for 3 hours and am no closer to a solution. What am I doing wrong?
In a module create the following function:
public function is_null(ctl as variant, nullreplace as string) as variant
if ctl is null then
is_null = nullreplace
else
is_null = ctl
end if
end function
In your query change your reference to a given field, yourField to is_null(yourField, "").
In a string enclosed in double quotes, this will need to be is_null(yourField, """") (it needs a double-quote to escape a double-quote, so 4 is 2 internally)

DCount with 2 criteria

I am using DCount to help display an error message if the data signals an error. I have it working with one criteria where a number is equal to another number. Now I wanted to add another criteria in there where another field, ReturnDate (this field is Text not Date/Time) is equal to a hyphen (-).
I'm just not really sure how to format it. I have this:
If DCount("*", "CrewTable", "KitNumber=" & _
Me.AssignKit.Value And "ReturnDate=" & _
"-") > 0 Then
Cancel = True
MsgBox "Kit is already assigned!"
AssignKit = ""
AssignKit.SetFocus
Else
...
The error pops up with a 'Type Mistmatch' and the debugger highlights the whole statment from 'If -> Then' and has an error pointing to the line with the hyphen in the quotes.
If DCount("*", "CrewTable", "ReturnDate='-' AND KitNumber=" & _
Me.AssignKit.Value) > 0 Then
It's easier to troubleshoot DCount errors when you store its Criteria option in a string variable.
Dim strCriteria As String
strCriteria = "ReturnDate='-' AND KitNumber=" & Me.AssignKit.Value
Debug.Print strCriteria
If DCount("*", "CrewTable", strCriteria) > 0 Then
If you had used this approach, Access would have alerted you to the fact that the original code which built the Criteria string was invalid. That should make it clearer that the problem wasn't due to the If condition, and it wasn't exactly a DCount problem either ... it was a problem with string concatenation.
Me.AssignKit.Value & " And ReturnDate=" & _

how to limit the characters in access to more than 255

How to limit the characters in access to more than 255? for example, I want it the memo or text box to limit it to max 300 characters.
In Access 2010
If you want to limit a memo field in a table to no more than 300 characters, open the table in design view and add this as the field's Validation Rule property.
Len([memo_field])<301
Substitute your field's name for memo_field. You can also add a Validation Text property to display a more user-friendly message when the rule is violated. With no Validation Text, that rule would produce this message ... which might not be very clear to a user:
*One or more values are prohibited by the validation rule 'Len([memo_field])<301' set for 'YourTableName.memo_field'. Enter a value that the expression for this field can accept.*
You also mentioned a text box. If it is a text box bound to a memo field, you can validate the character length in the text box's Before Update event. If the text box is named txtMemo_field:
Private Sub txtMemo_field_BeforeUpdate(Cancel As Integer)
If Len(Me.txtMemo_field) > 300 Then
MsgBox "Please limit data to maximum of 300 characters."
Cancel = True
End If
End Sub
After the message box, the cursor will be still located within the text box, and the user will not be allowed to move to another form field without supplying an acceptable value for txtMemo_field.
Just to address a point in #HansUp's answer:
Is Null Or Len([memo_field])<301 ... If you don't want to allow
Nulls, drop the "Is Null Or" part.
There is no need to explicitly test for nulls in a constraint. A constraint doesn't have to evaluate TRUE for it to be satisfied.
If the Access database engine (ACE, Jet, whatever) actually had a spec it would read like this:
A table constraint is satisfied if and only if the specified
search condition is not false for any row of a table.
According to three-valued logic required to handle nulls, the search condition LEN(NULL) < 301 evaluates to UNKNOWN and the table constraint would be satisfied (because UNKNOWN is not FALSE).
However, Access has no such spec, so we must test and see that the above assertions are indeed true (simply copy and paste into any VBA module, no references required, creates a mew blank mdb in the user's temp folder, then creates table, Validation Rule -- without the explicit test for null -- then attempts to add a null with success, Q.E.D.):
Sub WhyTestIsNull()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
With .ActiveConnection
Dim Sql As String
Sql = _
"CREATE TABLE Test (" & _
" ID INTEGER NOT NULL UNIQUE, " & _
" memo_field MEMO" & _
");"
.Execute Sql
End With
' Create Validation Rules
Dim jeng
Set jeng = CreateObject("JRO.JetEngine")
jeng.RefreshCache .ActiveConnection
.Tables("Test").Columns("memo_field") _
.Properties("Jet OLEDB:Column Validation Rule").Value = _
"LEN(memo_field) BETWEEN 1 AND 300"
jeng.RefreshCache .ActiveConnection
Sql = "INSERT INTO Test (ID, memo_field) VALUES (1, NULL);"
.ActiveConnection.Execute Sql
Sql = "SELECT * FROM Test;"
Dim rs
Set rs = .ActiveConnection.Execute(Sql)
MsgBox rs.GetString(2, , , , "<NULL>")
Set .ActiveConnection = Nothing
End With
End Sub
Change its Data type to Memo.
max field size of text field
Regards