Can't Update SQL on VBA Access - Getting a Mismatched Type Error on String - sql

I need a SQL Update a Long Text (Memo) on a Table but it's giving me an Error 3464, but have confirmed that the text I'm updating the Remarks into are Long Text (Memo) and what I'm updating is a string
Table Design
Table Contents
DoCmd.RunSQL "UPDATE aaTest1 SET aaTest1.test1Remarks = '" & CStr(Me.txtBox1) & "'WHERE ((aaTest1.testPrimK='" & CLng(PrimKNum) & "'));"
Error Message

As I comment, try below command-
DoCmd.RunSQL "UPDATE aaTest1 SET aaTest1.test1Remarks = '" & CStr(Me.txtBox1) & "' WHERE aaTest1.testPrimK=" & CLng(Me.PrimKNum)
Hope you are aware about variable declaring. More precise and clearer code here.
Private Sub cmdRunSQL_Click()
Dim strRemarks As String
Dim lnPrimKNum As Long
strRemarks = Me.txtBox1
lnPrimKNum = Me.PrimKNum
DoCmd.RunSQL "UPDATE aaTest1 SET test1Remarks = '" & strRemarks & "' WHERE testPrimK=" & lnPrimKNum
End Sub

Related

Access Compile error: Type mismatch on SQL Recordset Query

I've been chasing my tail on this SQL query for a record set. If I comment the query out, I do not receive the type mismatch error, so I'm relatively confident it is in this query. The query also works just fine in the Query window in Access (sans the quotes for getting it into VBA). I cannot, for the life of me, figure out why I'm getting a Compile error: Type mismatch on this. It always goes to the last '&'. I think I posted all the relevant code below. Please help? I do intend to move this to a string variable in the end, but I want to get it working first.
edit: I can address the type mismatch by making the change noted below. However, now I get a 424 error. If I output this to a debug window and paste the output into an SQL query window in access, I get the result I expect, but VBA doesn't like it for some reason.
Dim rs As DAO.Recordset
Dim FileNumber As String
FileNumber = Me.txtFileNumber
Set rs = "SELECT tblParentRecord.FileNumber, tblChildRecord.CombinedName " _
& " FROM tblParentRecord INNER JOIN tblChildRecord ON tblParentRecord.FileNumber = tblChildRecord.FileNumber " _
Added: & " WHERE (((tblParentRecord.FileNumber)= " & """" & Me.FileNumber & """" & ")) "
Removed:& " WHERE (((tblParentRecord.FileNumber) LIKE'" & FileNumber & "*" & "'))')
Try,
Dim rs As Recordset
Dim db As Database
Dim FileNumber As String
Set db = CurrentDb
FileNumber = Me.txtFileNumber
strSql = "SELECT tblParentRecord.FileNumber, tblChildRecord.CombinedName " _
& " FROM tblParentRecord INNER JOIN tblChildRecord ON tblParentRecord.FileNumber = tblChildRecord.FileNumber " _
& " WHERE tblParentRecord.FileNumber Like '" & FileNumber & "' "
Set rs = db.OpenRecordset(strSql)

Run-time error '3144': Syntax Error in Update Statement

I'm running into some issues with my update statement, the Add statement seems to work but I keep getting a syntax error in update. I am new to SQL and VBA so a lot of this probably looks like sphagetti code. If anyone can Identify what I did wrong that would be much appreciated. If there is a better way to do it, please let me know.
Private Sub btnSubmit_Click()
Dim mbrName As String
Dim mbrOffice As String
Dim mbrRank As String
Dim mbrOpType As String
Dim mbrRLA As String
Dim mbrMQT As String
Dim mbrPos As String
Dim sqlAdd As String
Dim sqlUpdate As String
If Me.opgMngRoster.Value = 1 Then
'-Set Middle Name to NMI if blank
If IsNull(Me.txtMidInit.Value) Then
Me.txtMidInit.Value = "NMI"
End If
'-Create Member's Name string in all uppercase
mbrName = UCase(Me.txtLastName.Value & ", " & Me.txtFirstName.Value & " " & Me.txtMidInit)
'-Member's Office
mbrOffice = Me.cbxOffice.Value
'-Member's Rank
mbrRank = Me.cbxRank.Value
'-Member's Operator Type
mbrOpType = Me.cbxOpType
'-Member's RLA
mbrRLA = Me.cbxRLA.Value
'-Member's MQT Program
mbrMQT = Me.cbxMQT.Value
'-Member's MQT Position
mbrPos = Me.cbxTngPos.Value
'ADD MEMBER TO ROSTER
sqlAdd = "INSERT INTO [ROSTER] (MEMBER, OFFICE, RANK, OPTYPE, RLA, [MQT-PROGRAM], [MQT-POSITION]) VALUES ('" & mbrName & "', '" & mbrOffice & "', '" & mbrRank & "', '" & mbrOpType & "', '" & mbrRLA & "', '" & mbrMQT & "', '" & mbrPos & "');"
DoCmd.RunSQL (sqlAdd)
'-Confirmation Msg
MsgBox ("Added: " & mbrName)
Else
'-Set Middle Name to NMI if blank
If IsNull(Me.txtMidInit.Value) Then
Me.txtMidInit.Value = "NMI"
End If
'-Create Member's Name string in all uppercase
mbrName = UCase(Me.txtLastName.Value & ", " & Me.txtFirstName.Value & " " & Me.txtMidInit)
'-Member's Office
mbrOffice = Me.cbxOffice.Value
'-Member's Rank
mbrRank = Me.cbxRank.Value
'-Member's Operator Type
mbrOpType = Me.cbxOpType
'-Member's RLA
mbrRLA = Me.cbxRLA.Value
'-Member's MQT Program
mbrMQT = Me.cbxMQT.Value
'-Member's MQT Position
mbrPos = Me.cbxTngPos.Value
'Update Member Data
sqlUpdate = "UPDATE [ROSTER] (MEMBER, OFFICE, RANK, OPTYPE, RLA, [MQT-PROGRAM], [MQT-POSITION]) VALUES ('" & mbrName & "', '" & mbrOffice & "', '" & mbrRank & "', '" & mbrOpType & "', '" & mbrRLA & "', '" & mbrMQT & "', '" & mbrPos & "');"
Debug.Print sqlUpdate
DoCmd.RunSQL sqlUpdate
MsgBox ("Updated: " & mbrName)
End If
End Sub
Several general coding and specific MS Access issues with your setup:
First, no need to repeat your VBA variable assignments for both If and Else blocks. Use DRY-er code (Don't Repeat Yourself).
Also, since you do not apply further calculations, there is no need to assign the majority of form textbox and combobox values to separate string variables. Use control values directly in query.
Use parameterization (an industry best practice) which is not only for MS Access but anywhere you use dynamic SQL in an application layer (VBA, Python, PHP, Java, etc.) for any database (Postgres, SQL Server, Oracle, SQLite, etc.). You avoid injection and any messy quote enclosure and data concatenation.
While languages have different ways to bind values to parameters, one way in MS Access is to use querydef parameters as demonstrated below.
Save your queries as stored objects with PARAMETERS clause (only compliant in MS Access SQL dialect). This helps abstract code from data.
Finally, properly use the update query syntax: UPDATE <table> SET <field>=<value> ...
Insert SQL Query (with parameterization, save once as stored query)
PARAMETERS MEMBER_Param TEXT, OFFICE_Param TEXT, RANK_Param TEXT, OPTYPE_Param TEXT,
RLA_Param TEXT, MQT_PROGRAM_Param TEXT, MQT_POSITION_Param TXT;
INSERT INTO [ROSTER] (MEMBER, OFFICE, RANK, OPTYPE, RLA, [MQT-PROGRAM], [MQT-POSITION])
VALUES (MEMBER_Param, OFFICE_Param, RANK_Param, OPTYPE_Param,
RLA_Param, MQT_PROGRAM_Param, MQT_POSITION_Param);
Update SQL Query (with parameterization, save once as stored query)
PARAMETERS MEMBER_Param TEXT, OFFICE_Param TEXT, RANK_Param TEXT, OPTYPE_Param TEXT,
RLA_Param TEXT, MQT_PROGRAM_Param TEXT, MQT_POSITION_Param TXT;
UPDATE [ROSTER]
SET MEMBER = MEMBER_Param, OFFICE = OFFICE_Param, RANK = RANK_Param,
OPTYPE = OPTYPE_Param, RLA = RLA_Param, [MQT-PROGRAM] = MQT_PROGRAM_Param,
[MQT-POSITION] = MQT_POSITION_Param;
VBA (no SQL shown)
Dim mbrName As String, myquery As String, mymsg As String
Dim qdef As QueryDef
'-Set Middle Name to NMI if blank
If IsNull(Me.txtMidInit.Value) Then
Me.txtMidInit.Value = "NMI"
End If
'-Create Member's Name string in all uppercase
mbrName = UCase(Me.txtLastName.Value & ", " & Me.txtFirstName.Value & " " & Me.txtMidInit)
If Me.opgMngRoster.Value = 1 Then
myquery = "myRosterInsertQuery"
mymsg = "Added: " & mbrName
Else
myquery = "myRosterUpdateQuery"
mymsg = "Updated: " & mbrName
End If
' ASSIGN TO STORED QUERY
Set qdef = CurrentDb.QueryDefs(myquery)
' BIND PARAMS
qdef!MEMBER_Param = mbrName
qdef!OFFICE_Param = Me.cbxOffice.Value
qdef!RANK_Param = Me.cbxRank.Value
qdef!OPTYPE_Param = Me.cbxOpType
qdef!RLA_Param = Me.cbxRLA.Value
qdef!MQT_PROGRAM_Param = Me.cbxMQT.Value
qdef!MQT_POSITION_Param = Me.cbxTngPos.Value
qdef.Execute dbFailOnError
'-Confirmation Msg
MsgBox mymsg, vbInformation
Set qdef = Nothing

Use SQL code in vba access

I use the following code in vba access to update a column of a table, but it is not working. Please help me.
Best regards.
Dim sqlupdate As String
sqlupdate = "UPDATE Assay" _
& "SET Assay.assay_repeat = " & 0 & "" _
& "WHERE (((Assay.[assay_repeat])= " & 1 & "));"
DoCmd.RunSQL sqlupdate
You have an extra double quote and are missing a couple of spaces - try it like this:
Dim sqlupdate As String
sqlupdate = "UPDATE Assay" _
& " SET Assay.assay_repeat = " & 0 & " _
& " WHERE (((Assay.[assay_repeat])= " & 1 & "));"
You just missed space chars at end of the table name and before where.
Dim sqlupdate As String
sqlupdate = "UPDATE Assay " _
& "SET Assay.assay_repeat = " & 0 & " " _
& "WHERE (((Assay.[assay_repeat])= " & 1 & "));"
Here is a great way to convert a SQL string to VBA code.
Creating the form
The form just needs two text boxes, and a command button. SQL statements can be quite long, so you put the text boxes on different pages of a tab control.
Create a new form (in design view.)
Add a tab control.
In the first page of the tab control, add a unbound text box.
Set its Name property to txtSql.
Increase its Height and Width so you can see many long lines at once.
In the second page of the tab control, add another unbound text box.
Name it txtVBA, and increase its height and width.
Above the tab control, add a command button.
Name it cmdSql2Vba.
Set its On Click property to [Event Procedure].
Click the Build button (...) beside this property.
When Access opens the code window, set up the code like this:
Private Sub cmdSql2Vba_Click()
Dim strSql As String
'Purpose: Convert a SQL statement into a string to paste into VBA code.
Const strcLineEnd = " "" & vbCrLf & _" & vbCrLf & """"
If IsNull(Me.txtSQL) Then
Beep
Else
strSql = Me.txtSQL
strSql = Replace(strSql, """", """""") 'Double up any quotes.
strSql = Replace(strSql, vbCrLf, strcLineEnd)
strSql = "strSql = """ & strSql & """"
Me.txtVBA = strSql
Me.txtVBA.SetFocus
RunCommand acCmdCopy
End If
End Sub
http://allenbrowne.com/ser-71.html
I recommend you use Recordsets.
Private Sub Update_My_Records(Parent As Object)
Dim Data_Recset As Object
Dim Parent_Reference As Object
Set Data_Recset = Parent_Reference.Application.DBEngine.Workspaces(0).Databases(0).OpenRecordset("SELECT * FROM Assay WHERE assay_repeat = " & 0 & ";", DB_OPEN_DYNASET)
Data_Recset.MoveLast
Data_Recset.MoveFirst
Data_Recset.Edit
Data_Recset.Fields("assay_repeat") = 1
Data_Recset.Update
Data_Recset.Close
Set Data_Recset = Nothing
End Sub
assumptions
Parent has reference to Access.Application. (I usually pass: Form.Module.Parent reference to Sub/Function)
the table or query "Assay" already exists.
You only need to update 1 row at a time
But if you want to use Queries In Your Form:
Private Sub Query_Definition_Update()
Dim Obj_Qdef As Object
Dim Query_Name As String
Query_Name = "Q_Assay"
Me.Form.Application.DBEngine.Workspaces(0).Databases(0).QueryDefs.Refresh
Set Obj_Qdef = Me.Form.Application.DBEngine.Workspaces(0).Databases(0).QueryDefs(Query_Name)
Obj_Qdef.SQL = Query_Update(1)
Debug.Print Obj_Qdef.SQL
Obj_Qdef.Execute
''When finished updating
Obj_Qdef.Close
Set Obj_Qdef = Nothing
End Sub
'------------------------------------------------------------'
Private Function Query_Update(New_Value as Integer) As String
Query_Update = "UPDATE Assay" & _
" SET Assay.assay_repeat = " & 0 & "" & _
" WHERE (((Assay.[assay_repeat])= " & New_Value & "));"
End Sub

Access VBA SQL where clause issue

I need some help. When i run the below query I get no results back if i include the Pkg number part of the where. When i run the query in Access it works fine.
example of vars
package number 1_282
Rptdt 201301
Dim db As Database 'generic database object
Dim rst As Recordset 'this is going to hold the query result
Set db = CurrentDb
Dim PKG As Double
Dim rptDT As Double
Dim wireDT As Date
Set rst = db.OpenRecordset("SELECT Max(tbl_Revision.Revision_Number) as Revision_Number FROM tbl_Revision" & _
" where (tbl_Revision.RUN_YR_MO=" & rptDT & ")" & _
" and (tbl_Revision.Package_Number=" & PKG & ")")
getRevision = rst!Revision_Number + 1
The PKG cant be a Double if you want 1_282 to work. So make it a string.
Also you will have to add quotes :
" where (tbl_Revision.RUN_YR_MO='" & rptDT & "')" & _

Updating Access Database from Excel Worksheet Data

I extract data from my Access database into an Excel worksheet using a macro. I first open a connection to the database, define my sql statement in a string var and then dump that data in a recordset:
Dim db As Database
Dim rs As RecordSet
Dim sql As String
Dim dbLocation As String
dbLocation = ThisWorkbook.Path & "\database\data.accdb"
Set db = OpenDatabase(dbLocation)
sql = "Select * FROM [Master Table]"
Set rs = db.OpenRecordSet(sql, dbOpenSnapshot)
If Not rs.EOF Then
Worksheets("Sheet1").Range("A1").CopyFromRecordset rs
End If
rs.Close
Set rs = Nothing
db.Close
Set db = Nothing
This works perfectly. I distribute this to some people and ask them to update fields. I then need to update the Access data with data that is passed back. The simple thing in terms of design is that the extracted excel data mirrors the access db in structure so the update query should be simple. Also there is a primary key, so I would just need to map on that field.
Any ideas how this can be done? Can I load the whole excel datasheet into a recordset and run some snazzy update query?
You need to loop over rows on sheet 1, and for each row make sql string that looks like:
"update [Master table] set
TableField1 = " & Range(Row, Col1).Value & ","
TableField2 = " & Range(Row, Col2).Value & ","
...
where IDTableField = " & Range(Row, IDColNum).Value
and then do
db.Execute thatString
PS: There are may be mistakes in my syntax. And you need to convert cell values to strings when making string.
An extension of shibormot's solution using DAO:
Set objConnection = CreateObject("DAO.DBEngine.36")
Set db = objConnection.OpenDatabase(strDBPath, blnExclusive, blnReadOnly, strPassword)
For Each row In Range("A1:C3").Cells
strSQL = "UPDATE table SET "
strSQL = strSQL & "Field1 = " & Chr(34) & row.Cells(1) & Chr(34) & ","
strSQL = strSQL & "Field2 = " & Chr(34) & row.Cells(2) & Chr(34) & ","
strSQL = strSQL & "Field3 = " & Chr(34) & row.Cells(3) & Chr(34)
Db.Execute
Next
Threw in the chr(34) for string data