How to include parameter in sql command in access VBA? - ms-access

I am new to Access VBA. I am passing a parameter (t) which is the result of a function(myfunc) to a table(myTable), it has ID and time column. Here is my code. It does not work. Where is the problem? Thanks.
Sub test()
Dim timetem As String
Dim t As String * 50
timetem = DLookup("[time]", "myTable", "[ID]=1")
t = myfunc(timetem)
DoCmd.RunSQL "UPDATE myTable SET [time] ='" & t & "'WHERE [ID] =1;"
End Sub

Please post the specific error code you're getting.
There are two issues with your code,
Firstly, what datatype is [time]?
If the time column in the database is not a string, this code will not work.
You should match the data type of timetem with the data type of the [time] column in your DB.
If time should be a date/time field then t should be escaped with # instead of '
I think there should also be a space here:
"'WHERE [ID]
should probably be
"' WHERE [ID]
Other pointers: You don't need to specify the size of t. Actually if you're trying to pass a date type as a string you probably would need to use the Format() function.
Also, DLookup is evil.

Related

field with memo datatype in a recordset

Is there any specific number of characters in string while use it in where clause?
SQL2 = "SELECT DISTINCT " & a & " AS MyString," & b & " FROM tempExtractedtbl"
Set rsGenerate = CurrentDb().OpenRecordset(SQL2)
Do While Not rsGenerate.EOF
SQL3 = "Select intId from IPDMst where TXTliteral='" &
rsGenerate.Fields("MyString").Value & "'"
Set temprsGenerate = CurrentDb().OpenRecordset(SQL3)
Here value of MyString in tempExtractedtbl is:
PO_EDGE_00503|Device Charge_1|Device
Type~Smartphone~Manufacturer~Apple~Model~iPhone 6~Capacity~32
GB~Colour~Space Grey~Blue Tick~FALSE~4GX~TRUE~Splash Proof~FALSE~Removable
Battery~FALSE~Expandable Memory~FALSE~HD Video
Recording~TRUE~NFC~TRUE~Featured~FALSE~Bonus Gift~FALSE~Operating
System~ios~Hot Buy~FALSE~Root Offering~Mobility Offer~
But when its stored in recordset, the value of MyString is trimmed to 255 characters. When i execute
?rsGenerate.Fields("MyString").Value
in immediate window, I get MyString as
PO_EDGE_00503|Device Charge_1|Device
Type~Smartphone~Manufacturer~Apple~Model~iPhone 6~Capacity~32
GB~Colour~Space Grey~Blue Tick~FALSE~4GX~TRUE~Splash Proof~FALSE~Removable
Battery~FALSE~Expandable Memory~FALSE~HD Video
Recording~TRUE~NFC~TRUE~Featured~F
And when I execute SQL3 I get following errors as MyString is trimmed.
Is there any limitation of recordset for memo field as MyString is a field having memo datatype. Is there a way out to store string having length more than 255 characters in a recordset and use it?
DISTINCT and Memo fields don't go together.
http://allenbrowne.com/ser-63.html
Access truncates the memo if you ask it to process the data based on the memo: aggregating, de-duplicating, formatting, and so on.
Uniqueness: Since you asked the query to return only distinct values, Access must compare the memo field against all other records. The comparison causes truncation.
Remove DISTINCT from the SELECT SQL.
You may need to create another query that selects the distinct values without the memo, and then use it as the source for another query that retrieves the memo without de-duplicating.

Invalid field Data type when use TableDef.CreateField Method VBA [duplicate]

This question already has answers here:
How do I create a decimal field in Access with Alter Table?
(3 answers)
Closed 6 years ago.
I am attempting to add a series of fields to a Access 2016 Table, but keep encountering the error:
Runtime error '3259'
Invalid field data type
I originally specified the data type as dbNumeric but changed it to dbDecimal to see if that made a difference. The solution given here for CreateFields did not solve my problem, though I did not try the SQL. It did not. Here is the code:
Sub BOD_Variables()
Dim myDBS
Dim myTable As TableDef
Dim myTableName As String
myTableName = "BOD_Data"
Set myDBS = CurrentDb
Set myTable = myDBS.TableDefs(myTableName)
Dim myField As Field
Dim myVariableNames As Variant
myVariableNames = Array("Blank_4_SampleVol", ... "BOD_ Concentration _OUT")
Dim iCount As Integer
For iCount = LBound(myVariableNames) To UBound(myVariableNames)
Debug.Print myVariableNames(iCount)
Set myField = myTable.CreateField(myVariableNames(iCount), dbDecimal) 'Originally specified dbNumeric for data type.
myTable.Fields.Append myField
Next
End Sub
I attempted to replace the call to the Array(index) with:
Set myField = myTable.CreateField("Blank_4_SampleVol", dbNumeric)
Still get the same error.
I tried specifying the length as discussed here, but that did not correct problem. Documentation on CreateField says it ignores field length when field type is dbNumberic.
Any ideas of what I am missing? Thanks in advance.
While it remains true that DAO does not seem to expose the required properties to create a Decimal field, even if we try using a DAO.Field2 object, the following ADOX code does create a Decimal field (tested with Access 2010):
Option Compare Database
Option Explicit
Sub AddNewDecimalField()
Dim cat As New ADOX.Catalog
cat.ActiveConnection = CurrentProject.Connection
Dim tbl As ADOX.Table
Set tbl = cat.Tables("MyTable")
Dim col As New ADOX.Column
col.Name = "MyNewDecimalField"
col.Type = adNumeric ' note: not adDecimal
col.Precision = 18
col.NumericScale = 8
tbl.Columns.Append col
End Sub
Or, we could just use a DDL query ...
CurrentProject.Connection.Execute _
"ALTER TABLE MyTable ADD COLUMN MyNewDecimalField DECIMAL(18,8)"
... as Andre suggests in his answer.
Follow the link in your linked question, and read the footnote #7 for DECIMAL:
[7] Not available in the Access query interface or DAO. Use ADO to Execute the DDL query statement.
So you'd use something like this:
strSQL = "ALTER TABLE myTable ADD COLUMN " & myVariableNames(iCount) & " DECIMAL (20,6);"
CurrentProject.Connection.Execute strSQL
Decimal fields have had (see comment below) their issues, see Avoid Using Decimal Field Size in Microsoft Access Tables
or http://allenbrowne.com/bug-08.html
Long or Double or Currency may be better options.

Table completely ignoring variable

Private Sub Form_Current()
Dim bytoffcut As Byte
Dim strCriteria
strCriteria = "[WOID] = " & Forms![frmAddStockBooking]![MouldWO]
bytoffcut = Nz(DMax("OffcutNo", "dbo_tblOffcuts", strCriteria), 0) + 1
MsgBox bytoffcut
Me.txtOffcut.Value = bytoffcut
Me.WOID.Value = Forms![frmAddStockBooking]![MouldWO]
Me.txtdate.Value = Now()
End Sub
Can anyone tell me why this is not working? The variable is behaving as expected where bytoffcut increments by one when i create a new record. But when I check the table the field bound to txtOffcut the field reads 1 instead of the incremented value.
EDIT: This code is being used in the On current property of the form. When I create a new record using a button on the form Dmax is used to find the highest offcut No value in a table and add one to it.
This appear to work in the form as the offcut no txtbox increments. But when i look at the table instead of having records with an increasing offcut no Instead all records read 1
Try sending your where clause in the DMax like this, assuming the WOID field in the table is an number type and not text or date.
"[WOID] = " & Forms![frmAddStockBooking]![MouldWO]
It would be better to evaluate your DMax() expression only once, especially if dbo_tblOffcuts is a large linked table without a usable index on [WOID].
If your DMax() expression can return a Null, use Nz() to transform the Null to zero. Then add one.
Dim bytoffcut As Byte
Dim strCriteria
strCriteria = "[WOID] = " & Forms![frmAddStockBooking]![MouldWO]
'Debug.Print strCriteria '
bytoffcut = Nz(DMax("OffcutNo", "dbo_tblOffcuts", _
strCriteria), 0) + 1
MsgBox bytoffcut
Me.txtOffcut.value = bytoffcut
This may not give you what you want when other users are editing dbo_tblOffcuts.
I have managed to solve the issue of multiple records being updated by creating a primary key for the table I am writing to.
I think that because Access could not uniquely identify the record it would edit all the records that met the criteria or something of the ilk. I am not entirely sure myself.

Adding logic to a sub form in Access?

I have a sub form in Access:
The CopyNo is a combobox that lets me select from the MovieCopies table. When I select one, I want the Title field to show the correct movie title associated to that copy's movie ID. I also want the format to show. When I select from DaysRented combobox, if I select 1 and the movie is New, I want it to display the price, if it is regular for 3 days display the correct price etc.
I'm just not sure how to give logic to the comboboxes.
If anyone could point me in the right direction of how to do this sort of thing in Access 2007 I'd really appreciate it.
Thanks
Something like this:
Private Sub cboCopyNo_AfterUpdate()
If Nz(Me.cboCopyNo, "") <> "" Then
Me.txtTitle = DLookup("Title", "MovieMaster", "MovieID = " & Me.cboCopyNo)
End If
End Sub
Private Sub cboDaysRented_AfterUpdate()
If Nz(Me.cboDaysRented, 0) > 0 Then
Dim strType as String
strType = DLookup("[Type]", "MovieMaster", "MovieID = " & Me.cboCopyNo)
If Me.cboDaysRented = 1 Then
Me.txtPrice = DLookup("Price1Day", "Price", "[Type] = '" & strType & "'")
Else
Me.txtPrice = DLookup("Price3Day", "Price", "[Type] = '" & strType & "'")
End If
End If
End Sub
Couple notes. Some of your field names are reserved words in certain databases, such as "Type". I highly recommend you try to use field names that are not reserved words in Access or SQL server.
DLookups are not necessarily the fastest way to lookup data but will likely be fast enough for what you're trying to do here. Sometimes I create my own DAO recordset and lookup the values I want rather than using DLookup. It's basically like writing your own DLookup function.
DLookup uses SQL language so your syntax in the third argument, the WHERE clause, needs to match SQL. If the field in your WHERE clause is text/string you'll need to use a single quote on either side of the value (as shown above around the strType variable). If it is a number field you will not need the quotes. If it's a date you'll need hash signs (#).

(Error 3071) Access

I'm trying to search for the Course ID by checking the the faculty ID and Course ID in my Course table. Its a simple query but when launched I receive a
(This expression is typed incorrectly, or it is too complex to be evaluated. For example, a numeric expression may contain too many complicated elements. Try simplifying the expression by assigning parts of the expression to variables. (Error 3071)
The VB script I'm using looks like this.
Private Sub Course_ID_DblClick(Cancel As Integer)
Dim x As Integer
Dim y As String
Dim z As Integer
x = Me.Faculty_ID.Value
Me.Course_ID.RowSource = "SELECT Course.[Course ID] FROM Course WHERE Course.[Course Name]=['Course']AND Course.[Faculty ID]='" & x & "'"
End Sub
I think you are getting this message because you are using wrong delimiters and confusing terminology in object names (where field content 'course' and table name [course] are the same.
I guess your datasource is an ms-access database. You should then use the " (double quote) as value separator (you'll have to double the sign inside the expression) for text, and nothing for numbers. your select instruction could then look like:
"SELECT Course.[Course ID] FROM Course WHERE Course.[CourseName]=[""Course""] AND Course[FacultyID]=" & x
Add a 'debug.print Me.Course_ID.RowSource' to check the final string that should look like:
SELECT Course.[Course ID] FROM Course WHERE Course.[CourseName]=["Course"] AND Course[FacultyID]= 3
There should be no brackets around your string literals:
Me.Course_ID.RowSource = "SELECT Course.[Course ID] FROM Course WHERE Course.[Course Name]='xyz' AND ...
Also, you can use either single or double quotes as string delimiters in an access query.