Setting Validation rules to multiple fields using VBA code returns error 3309 (too large) - ms-access

I would like to ask you for help with (edited) VBA code I found while searching for solution. My goal is to add validation rule to multiple field of table at once by VBA code. I have to use VBA code because there is so many fields and manual input would be insane.
Validation rule: NOT LIKE "*"+Chr(10)+"*" OR "*"+Chr(13)+"*" OR "*"+Chr(9)+"*"
(user can't save "enter", "ctrl+enter" and "tabulator")
For using this rule in VBA function the syntax is quite different but input to MS Access is correct.
My VBA code (not directly my, I found it and edit to my needs)
Public Function SetFieldValidation()
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Dim strValidRule As String
Dim strValidText As String
Dim bytNumOfFields As Byte
strValidRule = "NOT LIKE " & Chr(34) & "*" & Chr(34) & "+Chr(10)+" & Chr(34) & "*" & Chr(34) & " OR " & Chr(34) & "*" & Chr(34) & "+Chr(13)+" & Chr(34) & "*" & Chr(34) & " OR " & Chr(34) & "*" & Chr(34) & "+Chr(9)+" & Chr(34) & "*" & Chr(34)
strValidText = "Some error msg"
Set dbs = CurrentDb
Set tdf = dbs.TableDefs("Table_Name")
For bytNumOfFields = 0 To tdf.Fields.Count - 1
With tdf.Fields(bytNumOfFields)
If .Name <> "Record ID" Then
.ValidationRule = strValidRule
.ValidationText = strValidText
End If
End With
Next
End Function
In the past this script works with rule NOT LIKE "*"+Chr(10)+"*" OR "*"+Chr(13)+"*".
Than tried to add OR "*"+Chr(9)+"*".
Since this modification the MS Access (VBA) returns error: Property value is too large. (Error 3309) while I run the script. When I tried return to previous version of script without +Chr(9)+, the error still remains (even I succesfully used this script in the past and validation rules are set in another tables).
I'm really beginer in VBA, honestly I only need to setup this rule to all field of all tables. Can someone experienced tell me what's wrong in the code?
Thank you very much.

I suggest not using Chr(). Since Chr will always return the same value for a particular number, e.g. Chr(65) always returns A, I don't think you need to use the function to get the value you want. So try setting your strValidRule as one long static string with the characters returned by the Chr() functions hard coded.

I did a research and probably the problem is somewhere else - looks like error in table design of specific table.
1.) First test: At first I tried to debug strValidRule string and compare two approaches for string (my and with quotes as #Rominus advised). The results are same but quoString is smoother approach. Than I run script (tried both approaches). Error msg said 'Property Value Too Large' error 3309 and the old valid rules remains in table design unchanged (rules were set in the past and remains).
Sub teststring()
chrString = "chrString: NOT LIKE " & Chr(34) & "*" & Chr(34) & " +Chr(10)+ " & Chr(34) & "*" & Chr(34) & " OR " & Chr(34) & "*" & Chr(34) & " +Chr(13)+ " & Chr(34) & "*" & Chr(34)
Debug.Print chrString
quoString = "quoString: NOT LIKE ""*"" +Chr(10)+ ""*"" OR ""*"" +Chr(13)+ ""*"""
Debug.Print quoString
End Sub
2.) Second test: From my script above I firstly 'commented' values of strValidRule and strValidText by ' and add empty values "". Script run without error msg and added empty values.
Than I 'uncommented' the values and run script with values mentioned above (quoString approach and some msg for strValidText). Scritp run with error msg 'Property Value Too Large' error 3309. BUT, when I checked table design, the valid rules were properly set and working even the error msg popped up.
3.) Third test: I tried to use script in another table and run it without previously adding empty values described in step 2. (because in table were set old valid rules too). Script successfully overwrote old valid rules by new ones without msg of error 3309.
So, I found the way how to set valid rules but there is still some bug that shows error msg in specific table. Don't know how to fix it but I hope it haven't affect of my main goal (setting new working valid rules).

Related

Access: Filtering form on field - fails when fields contains an apostrophe

I have a filter on a continuous form that uses a Combo Box to select records to match; the code is:
Private Sub SelectHospitalCbo_AfterUpdate()
Me.Filter = "[ContactHospital] = " & "'" & Me.SelectHospitalCbo & "'"
Me.FilterOn = True
End Sub
This was working fine until I discovered that if the ContactHospital field includes an apostrophe (e.g. Children's Hospital) I get an error message:
Run-time error '3075':
Syntax error (missing operator) in query expression '[ContactHospital] = 'Children's Hospital".
I understand why the error is occurring, but I can't find a workaround. A recent question on this forum seemed to have a similar problem to mine, but there were no answers. Does this mean I can't get around it?
In case anyone wants to suggest removing all the apostrophes form the hospital names, I would consider that, but unfortunately this database interacts with a (much larger) database where the hospital names can't be changed and have to match, so that's not an option for me.
Any help from more experiences Access developers appreciated!
Options:
filter by numeric hospital ID instead of its name
"[ContactHospital] = '" & Replace(Me.SelectHospitalCbo, "'", "''") & "'"
"[ContactHospital] = """ & Me.SelectHospitalCbo & """"
"[ContactHospital] = " & Chr(34) & Me.SelectHospitalCbo & Chr(34)

VBA Access: No value given for one or more required parameters

I know, there are lots of answers out there for this problem which should be trivial, but I did not find the right one. Here is my problem:
I open a record set with the following select statement:
SELECT twinecellar.produktnavn, twinecellar.land,
twinecellar.produkttype, twinecellar.år,
twinecellar.antall, twinecellar.poeng,
twinecellar.Picture, twinecellar.KR,
twinecellar.Poengsum, twinecellar.Sum
FROM twinecellar
WHERE (((twinecellar.land)=forms!fmainview!list13)
And ((twinecellar.produkttype)=forms!fmainview!list15))
ORDER BY twinecellar.poeng;
In the immidiate window I see that list 13 contains "france" and list 15 contains "red"
When I create a new Query with this statement, it's working, however, on the rst.Open gsStrQuery I get this error. gsStrQuery contains the select string.
Here is the code:
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Set conn = CurrentProject.Connection
Set rst = New ADODB.Recordset
rst.CursorType = adOpenDynamic
rst.ActiveConnection = conn
rst.Open gsStrQuery
Anybody out there with a good idea about this issue?
When you build your SQL string, concatenate the "parameters" values into the string.
gsStrQuery = "SELECT twinecellar.produktnavn, twinecellar.land, " & _
"twinecellar.produkttype, twinecellar.år, " & _
"twinecellar.antall, twinecellar.poeng, " & _
"twinecellar.Picture, twinecellar.KR, " & _
"twinecellar.Poengsum, twinecellar.Sum " & _
"FROM twinecellar " & _
"WHERE (((twinecellar.land)= '" & forms!fmainview!list13 & "') " & _
"And ((twinecellar.produkttype)= '" & forms!fmainview!list15 & "')) " & _
"ORDER BY twinecellar.poeng;"
That way your parameter values are hard coded into the string before you try to open the query.
(Also note: I added single quotes around your parameters to indicate they are strings.)
(Also also note: & _ is a line continuation for VBA so your SQL string concatenates properly. This allows you have a readable SQL code that's nicely indented.)
________________________________
There is also a way to use your current gsStrQuery and assign parameters values to the ADO recordset. (But I find the above Replacement method much easier to read when going back to review the code. The only drawback is you have to rebuild your SQL string each time your parameters change. But that overhead is minimal for non complicated queries.)
However, if you really want to use ADO parameters, you can find a useful description here.
Hope that helps :)

strSQL formatting in Access

I am having some trouble formatting an SQL string in Access, I can never seem to debug these syntax issues with SQL strings. I have this string:
strSQL = "SELECT * FROM FXData WHERE ShortCode=" & Forms!FXVolatility.cboCurve.Value & " AND MaxOfMarkAsOfDate=#" & MaxOfMarkAsofDate & "# ORDER BY MaxOfMarkAsOfDate "
debug.print strSQL
Set rs = CurrentDb.OpenRecordset(strSQL, Type:=dbOpenDynaset, Options:=dbSeeChanges)
which prints
SELECT * FROM FXData WHERE ShortCode=USD.XS AND MaxOfMarkAsOfDate=#3/31/2016# ORDER BY MaxOfMarkAsOfDate
However this gives me a "Too Few Parameters, expected 1" error.
All the fields and their associated values that are referenced in strSQL exist in the referenced table. What could the error be?
Also if you've got any resources on how to debug/identify these specific access SQL formatting issues I'd be happy to hear them.
In SQL, strings need to be put in single or double quotes. Thus, your output should look like this:
... WHERE ShortCode='USD.XS' ...
Thus, your code becomes:
strSQL = "SELECT * FROM FXData WHERE ShortCode='" & _
Replace(Forms!FXVolatility.cboCurve.Value, "'", "''") & _
"' AND MaxOfMarkAsOfDate=#" & MaxOfMarkAsofDate & _
"# ORDER BY MaxOfMarkAsOfDate "
The Replace ensures that any single quotes occurring within cboCurve.Value are properly escaped.
Note that it is recommended to use parameters instead of string concatenation to "fill" values into an SQL statement. An example for how to do this in MS Access can be found in the answer to this question:
VBA OpenRecordset Producing Too few parameters. Expected 2. Error

DoCmd.RunSQL mySql got Run-time error '3464'

I have this simple code of vba access to update product in the database. But when I debug, it stops at the DoCmd statement and got run-time error. I've made research about this kind of error and code, and had changed the code but still caused an error. Below is my simple code to update the product value.
Sub UpdateProduct()
Dim mySql As String
mySql = "UPDATE " & Forms!UPDATE_PRODUCT!cbxLensType _
& " SET LOT_NO = " & Forms!UPDATE_PRODUCT!txtLotNo _
& " WHERE EAN_CODE = " & Forms!UPDATE_PRODUCT!txtEan & ";"
DoCmd.RunSQL mySql
End Sub
Could you help me to explain what is the problem to my code? Is it because of the update syntax?
Thanks in advance.
**New to access vba
Since EAN_CODE is Text type you need to enclose it inside single quotes.
Sub UpdateProduct()
Dim mySql As String
mySql = "UPDATE [" & Forms!UPDATE_PRODUCT!cbxLensType _
& "] SET LOT_NO = " & Forms!UPDATE_PRODUCT!txtLotNo _
& " WHERE EAN_CODE = '" & Forms!UPDATE_PRODUCT!txtEan & "';"
DoCmd.RunSQL mySql
End Sub
If LOT_NO is also a Text type, make sure that it is also enclosed in Single quotes.

Error 3061 Too few parameters 2 expected

I have been facing the error 3061 with error message "Too few Parameters: Expected 2". I have done all of the following to resolve the issue but still couldn't it.
I ran the query in SQL mode and it gives me result
I checked all the field names
I checked all the "&" s are placed. I find them correct.
Here is my code:
Private Sub cmbYear_Change()
Dim db As Database
Dim rs As DAO.Recordset
Dim Query As String
Query = " SELECT Yrs_Teaching, Highest_Edu, AD_Descr FROM ClassSurvey" & _
" WHERE ClassSurvey.Program/School_ID = " & Me.cmbProgId.Value & _
" AND ClassSurvey.ClassID = " & Me.cmbClassId.Value & _
" AND ClassSurvey.Teacher_ID = " & Me.cmbTeacherID.Value & _
" AND ClassSurvey.SYear = " & Me.cmbYear.Value
Set db = CurrentDb
Set rs = db.OpenRecordset(Query)
If rs.RecordCount > 0 Then
Me.TB1 = rs!Yrs_Teaching
Me.TB2 = rs!Highest_Edu
Me.TB3 = rs!AD_Descr
Else
Me.TB1 = "N/A"
End If
Set rs = Nothing
Set db = Nothing
End Sub
It appears your table includes a field named Program/School_ID. Bracket that field name in the SELECT statement so the db engine can properly recognize it as one field name.
That change might be all you need. But if you have another problem, give yourself an opportunity to examine the completed SELECT statement you're giving to the db engine. It might not be what you expect.
Dim db As Database
Dim rs As DAO.Recordset
Dim strQuery As String
strQuery = "SELECT cs.Yrs_Teaching, cs.Highest_Edu, cs.AD_Descr FROM ClassSurvey AS cs" & _
" WHERE cs.[Program/School_ID] = " & Me.cmbProgId.Value & _
" AND cs.ClassID = " & Me.cmbClassId.Value & _
" AND cs.Teacher_ID = " & Me.cmbTeacherID.Value & _
" AND cs.SYear = " & Me.cmbYear.Value
Debug.Print strQuery
Set db = CurrentDb
Set rs = db.OpenRecordset(strQuery)
If you get an error, you can go to the Immediate window (Ctrl+g), copy the statement text from there, open a new query in the query designer, switch to SQL View, paste in the statement text and try running it there. This tip is especially useful when the db engine complains about a missing parameter because when you try to run the query from the designer, Access will show you an input box asking you to supply a value and that box also contains the name of whatever Access thinks is the parameter.
I came across this when I was looking for a solution to the same problem. Turns out one of the values from a control on the form was not passing the value to the statement, sending it to the debug window (Debug.print) helped me spot the problem after a long time because I was using a global variable which the sql query was parsing. So load your controls' values into variables first!
This error may be because the column names in the query have special characters. Try surrounding the column names with square brackets in the SQL query. Column name with special symbols should be within square brackets and variables should be inside single quotes.
I had this issue too, I realized it was because I did not put quotes around my variables.
This was fixed by adding '& Chr(34)' around my variables
My fixed code looks like:
TextProducer = [Forms]![MyFormName]![TextInputBoxName]
strQuery = "SELECT FILEMASK" & _
" FROM TABLE_NAME" & _
" WHERE Producer = " & Chr(34) & TextProducer & Chr(34)