I have a question with my converting in VBA. I made a button in a form and when I press it, it should make an update in my database table, but I get an ERROR:
arithmetic overflow error converting numeric to data type numeric
How can solve this problem? Here is my code:
Private Sub Inserare_Click()
Dim strSQL As String
Dim rst As New ADODB.Recordset
strSQL = "UPDATE dbo.Soferi_test SET number= '" &
Me![subform_soferi].Form!certificat_cipti & _
"',drivers= '" & Me![subform_soferi].Form!categorii_permis & _
"' WHERE IDNO = " & Forms!Forma_redactare_soferi!IDNO
Call AttServ(strSQL, rst)
MsgBox ("Datele au fost introduse cu success")
End Sub
number is a reserved word. Bracket that name in your UPDATE statement so the db engine knows it's supposed to be a field name.
strSQL = "UPDATE dbo.Soferi_test SET [number]= '" &
If that change doesn't resolve the problem, inspect the completed SQL statement. Insert this line after you store the string to strSQL.
Debug.Print strSQL
You can view that output in the Immediate window (go there with Ctrl+g). You can then copy that statement text into SQL View of a new Access query for testing. Add the statement to your question if you can't get it to work properly and tell us whether you get the same or different error message.
It may also help to show us the code from your AttServ procedure which uses strSQL.
I think the problem is in the field type of the table you are trying to update.
Example: If you try to set the value of a small integer field to a long integer, value, Access will throw an error.
Check the type of your fields and set them to the appropriate type.
Other think that can be wrong is the value of the text boxes. Just to be sure, try to convert the values.
Example: Cdbl(Me![subform_soferi].Form!certificat_cipti) will convert the string in your text field to a double value.
Also, I recommend you use the value attribute of your text boxes:
Me![subform_soferi].Form!certificat_cipti.Value
or
CDbl(Me![subform_soferi].Form!certificat_cipti.Value)
Notice that if you use the "conversion" functions (CDbl, CInt, CDate, etc.) an error will be thrown if the conversion fails (for example, trying to convert 12abc to an integer will fail)
Related
This might be a basic formatting question, but for some reason I can't figure out a way get around it. The scenario that I have is that I want to use VBA to find the highest number from one field in a table in a given category (identified in another field in the same table). I have about eight categories, each with different numbers (e.g.)
ATD 500
ATD 250
ATD 700
MLK 500
MLK 120
PTO 900
I believe that the best way to do this would be to the DMAX Function, but for some reason I'm running into syntax errors no matter how I try to write it.
The code I'm work with so far is:
Dim HighestNumber As Variant
Dim HighCategory As Integer
HighCategory = InputBox("Please enter data", "ENTER", "ENTER")
HighestNumber = DMAX("[SaleValue]", "SalesTable", "[SalesCategory] = '" & HighCategory & "'")
(To clarify, [SaleValue] and [SalesCategory] are two columns in the access table "SalesTable", and I'm trying to set it up so that the user can enter a SalesCategory and get the highest SaleValue for that category. I'd like to be able to store that value somewhere for later use as well.)
Whenever I run this, I hit a Run-Time error '5', invalid procedure call on the last line. I'm fairly sure that it's a syntax error but I can't make heads or tales of why. I tried reading this site:
https://msdn.microsoft.com/VBA/Access-VBA/articles/application-dmax-method-access
But they focus on hardcoded criteria and I can't find a good example of how to use DMax where the criteria should be designated by the user.
Thanks for any help you can provide!
EDIT: Changing the code as follows produces the same error
Dim HighestNumber As Long
Dim HighCategory As String
HighCategory = InputBox("Please enter data", "ENTER", "ENTER")
HighestNumber = DMAX("[SaleValue]", "SalesTable", "[SalesCategory] = '" & HighCategory & "'")
You've specified that the HighCategory is an Integer, however this should either be a string or a variant, as isn't this "ATD" etc? Also, your HighValue variable is a variant, and should probably be a numeric (I'd actually consider using a LONG here rather than an INT).
I am assuming that an example of a SalesCategory would be "ATD" and therefore the highest value (and what DMAX would return) should be 700?
Here's a minor tweak to the code, this should work as you intended. I'm also checking for invalid entries here (Nz), and converting the result to a Long Integer (CLng)
Dim lngHighestNumber As Long
Dim strHighCategory As String
strHighCategory = InputBox("Please enter data", "ENTER", "ENTER")
lngHighestNumber = Nz(CLng(DMAX("[SaleValue]", "SalesTable", "[SalesCategory] = '" & strHighCategory & "'")), 0)
databasename = "qryDataExport"
Dim grpfield As String
grpfield = "Group"
Dim keys As DAO.Recordset
groupcmd = "SELECT [" & databasename & "].[" & grpfield & "] FROM [" & databasename & "] GROUP BY [" & databasename & "].[" & grpfield & "]"
Set keys = CurrentDb.OpenRecordset(groupcmd, dbOpenSnapshot)
The above produces "Error 3061: Too few parameters. Expected 13." when run. My reading thus far has heavily implied that this is likely a spelling issue with improper field titles or an issue caused by improper quotations in the line defining groupcmd.
I have attempted the following formats for databasename:
CurrentDb.Queries.qryDataExport
CurrentDb!Queries!qryDataExport
And the above "qryDataExport". The latter two provide no error messages, while the first does not compile. I have confirmed that there is a column titled Group in both the main table and in qryDataExport.
The module being used is from this Google Code page.
(EDIT: Full edited module as of this time: http://pastebin.com/TJip86ED)
From what I've seen, I expect this is an incredibly obvious formatting error in the databasename definition, but I haven't got enough experience with VBA to spot it and I'm running out of ideas. Any suggestions would be greatly appreciated.
EDIT2: The content of generateKML() is now in ExportToKMLButton_Click(), where ExportToKMLButton is a Button on the Form DW_Form. While DW_Form is open, the query qryDataExport is usable, but when the form is closed, the query prompts for the 13 parameters mentioned in the error message.
It sounds like your qryDataExport query references controls on an Access form, perhaps similar to this one ...
SELECT *
FROM YourTable
WHERE some_field = Forms!Form1!YourTextBox
If Form1 is open (in Form View), I can run that query from Access' query designer, and it will resolve the reference to the form control.
However, if I try to use the exact same query with OpenRecordset, the reference is not resolved and, in that context, Access interprets it to be a parameter for which I have not supplied a value.
For your query with multiple control references, you can create a temporary QueryDef based on your SELECT statement, and loop through its Parameters collection, supplying each parameter value with Eval() of the parameter's .Name And finally call the QueryDef.OpenRecordset method to load your recordset:
Dim prm As DAO.Parameter
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.CreateQueryDef(vbNullString, groupcmd)
For Each prm In qdf.Parameters
prm.Value = Eval(prm.Name)
Next
Set keys = qdf.OpenRecordset
The way you use databasename is correct (databasename = "qryDataExport"), qryDataExport is likely filtering data using values from the form... that's why when you execute the query independently, the query finds it is missing 13 paramenters that it takes from said form.
You can run this procedure in a Click() event for a button within the form, it should work.
I am using VBA macro to make a table. First, I am inputting a date "PeriodEnd", this date filters a base table using a query. Then, I am making a second table and populating that table with (a) the results of the query, and (b) about 30 calculated fields based on the records of the query and other related tables.
My problem is that I am trying to put the PeriodEnd date in the table name and I can't seem to get the Syntax right. I am a VBA beginner, so thanks for the help. My VBA looks like as follows:
....
Dim db as DAO.Database
Dim PeriodEnd as Date
Dim PerStr as String
Set db = CurrentDb()
PeriodEnd = #12/31/2013#
PerStr = Format(PeriodEnd, "yyyy-mm-dd")
db.Execute "CREATE TABLE TblName_" & PerStr _
& " (Field1 as LONG)
I've run this with syntax where the table name is static and I don't get any errors. When I run with the variable table name I get "Run-time error '3290': Syntax error in CREATE TABLE statement."
Also, is there a better way to structure this? The only difference in these table will be the period end date--and the impact that a different period end date has on the underlying calculations I am forming in the VBA (functions not supported within the SQL).
Any advice on whether this should be structured instead as a query or a report (no experience yet with reports)?
You're attempting to create a table whose name includes dashes (because of the date format). You will need to bracket that name.
db.Execute "CREATE TABLE [TblName_" & PerStr _
& "] (Field1 as LONG)"
Also make sure to include the quotation mark at the end of the statement as I did above.
But consider using a variable to hold your CREATE statement. Then you can Debug.Print the variable to inspect the statement you're asking the db engine to execute.
Dim strDdl As String
strDdl = "CREATE TABLE [TblName_" & PerStr & "] (Field1 as LONG)"
Debug.Print strDdl
db.Execute strDdl
I've got a subform (RegistrationFsub) based on table Registration. It's purpose is to create a one-to-many relationship between a person and the year(s) they have enrolled in the group.
When a mom enrolls in a new year, I have a command button that is supposed to add a new line to the table Registration with MomID (from the parent form: MomsFsub) and the start date of the current enrollment year (YearStart, from table Year). Since the current enrollment period is represented by the latest date, I want to use the Max() command to retrieve it from YearT. I tried the following code:
Dim db As DAO.Database
Dim sqlSTR As String
Dim IDvar As String
'new code added since question posted
Set db = CurrentDb
Call MsgBox (Max(YearT!YearStart), vbOKonly)
'MsgBox checks value returned for Max(YearStart)
'end new code
IDvar = CStr(MomID)
sqlSTR = "INSERT INTO Registration(YearStart, MomID) SELECT Max(YearStart), "_
& IDvar & " AS expr1 FROM YearT;"
'new: debug statement
Debug.Print sqlSTR
db.Execute sqlSTR
And I got an "Object variable or With block variable not set" error. What am I doing wrong?
Edit: Setting the db to Currentdb fixes the Object variable error, but now returns a "Too few parameters" error. The original table name "Year" has been changed to "YearT," since I only reference it in this one bit of code anyway.
Update
Now that I've fixed RegistrationFsub, it seems that the button also inserts data currently displayed in other controls on the form. So if the 2012 entry has RID = 1 and Leader = True, the above code creates an entry in Registration that also has RID = 1 and Leader = True. How can I keep those other fields blank?
The object variable error is because you didn't Set db to anything before you attempted db.Execute. Do this first ...
Set db = CurrentDb
If you later get an error with Execute, it may be because Year is a reserved word. Enclose that table name in square brackets to avoid confusing the db engine.
sqlSTR = "INSERT INTO Registration(YearStart, MomID) SELECT Max(YearStart), "_
& IDvar & " AS expr1 FROM [Year];"
If you are adding a new record based on the Mom's current new entry, you need to take the current time: Now() and parse the year off of it..
Year(Now())
Looking for Max(YearStart) could be looking for a record that happened 5 years ago..
sqlSTR = "INSERT INTO Registration(YearStart, MomID) SELECT Max(YearStart), "_
& IDvar & " AS expr1 FROM Year;"
I think you need to update the code to two different operations:
sqlSTR = "INSERT INTO Registration(Year(Now()), MomID)"
run your code..
Then do a..
sqlSTR= "SELECT Year(Now()), " & IDvar & " AS expr1 FROM [Year];"
The most relevant answer was deleted before it could be selected, so I shall paste the content here:
The object variable error is because you didn't Set db to anything before you attempted db.Execute. Do this first ...
Set db = CurrentDb
If you later get an error with Execute, it may be because Year is a reserved word. Enclose that table name in square brackets to avoid confusing the db engine.
sqlSTR = "INSERT INTO Registration(YearStart, MomID) SELECT Max(YearStart), "_
& IDvar & " AS expr1 FROM [Year];"
For "too few parameters", add Debug.Print sqlSTR after the sqlSTR = ... line.
But before the Execute command
Run the code and go to the Immediate window (Ctrl+g). Copy the SQL text, create a new query in the query designer, switch to SQL View, and paste in the SQL text. When you run that query, Access will pop up an input box asking you to supply a value for the parameter. That box also include the name of whatever Access thinks is the parameter.
The trouble here is that YearStart had a different field name in table Year.
Many thanks for the clear and helpful answer.
I'm not sure if this is the right site to post this question, but here it goes...
In Access 2007 I get the error "Runtime Error '3061': Too few parameters. Expected 1" on this piece of VBA code:
Private Sub btnCheck_Click()
Dim rs As Recordset
Dim db As Database
Dim id As String
Dim query As String
MsgBox ("one")
Set db = CurrentDb()
id = Me.UniqueID.Value
query = "SELECT [Unique_ID] from tblPatients WHERE [Unique_ID] =" & id
MsgBox (id)
Set rs = db.OpenRecordset(query) <<<<<HIGHLIGHTED LINE
If IsNull(rs) Then
Me.lblCheck.Caption = "NEW"
Else
Me.lblCheck.Caption = "EXISTS"
End If
End Sub
The data source is a table, not a query. Any help would be much appreciated!
There is no field named Unique_ID in your table tblPatients. If you posted all of your code then that is the only possible explanation.
EDIT: Your comment confirmed my suspicions:
I just triple checked :P Table name: tblPatients Column name: Unique ID
You added an underscore in your code that did not exist in your field name. You are correct in using square brackets, but the correct code should be:
query = "SELECT [Unique ID] from tblPatients WHERE [Unique ID] =" & id
Please note the removed underscores. Alternatively (and I'd say preferably if you are in the early stages of design), you can rename the field in the table to either Unique_ID or UniqueID and save yourself a good deal of hassle.
A Few things can cause this error. A common error is misspelled table names and field names.
I would check tblPatients is spelled correctly or that there is no prior suffix like dbo.tblPatients required if the table is linked to a Server Connection.
As well we are assuming the id is a number and isn't a text field which would cause an error if you do not have the correct quotes. ie.
it would instead read
query = "SELECT [Unique_ID] from tblPatients WHERE [Unique_ID] = '" & id & "';"
Lastly, try to place ";" like I did in the line above.
I suggest you add a Debug.Print statement to your code like this:
query = "SELECT [Unique_ID] from tblPatients WHERE [Unique_ID] =" & id
Debug.Print "query: " & query
The reason for that suggestion is Debug.Print will print your SQL statement to the Immediate Window. (You can use the Ctrl+g keyboard shortcut to get to the Immediate Window.) Then you can view the completed string you're asking OpenRecordset to use. Often just seeing that string (rather than trying to imagine what it should look like) will let you spot the problem. If not, you can copy the string from the Immediate Window and paste it into SQL View of a new query ... the query designer can help you pinpoint syntax errors ... or in this case, I think it may alert you to which item in your query the database engine doesn't recognize and suspects must therefore be a parameter. And if that step still doesn't resolve the problem, you can paste the string into your question on Stack Overflow.
Finally, I think you may have a logic error with IsNull(rs) ... because rs has been declared a recordset, it will never be Null. In the following example, the SELECT statement returns no records. And the Debug.Print statement says IsNull(rs): False both before and after OpenRecordset.
Public Sub RecordsetIsNeverNull()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSql As String
strSql = "SELECT * FROM tblFoo WHERE 1 = 2;"
Set db = CurrentDb
Debug.Print "IsNull(rs): " & IsNull(rs)
Set rs = db.OpenRecordset(strSql)
Debug.Print "IsNull(rs): " & IsNull(rs)
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
Edit: According to Problem names and reserved words in Access, query is an Access reserved word. I don't actually think that is the cause of your problem, but suggest you change it anyway ... perhaps strQuery.