Compile error: Syntax error -MS ACCESS 2010 VBA error - vba

Microsoft Access 2010 database gives me the following error
"Compile error: Syntax error"
In VBA window for this form it highlights the following line of code at line 3 "strSQL = "SELECT PID from tblMSCSPersonnel WHERE SSN = '" & Me!TextSSN & "';" "
The entire code is below
Private Sub Form_Current()
Dim strSQL As String
strSQL = "SELECT PID from tblMSCSPersonnel WHERE SSN = '" & Me!TextSSN & "';"
Set rs = CurrentDb.OpenRecordset(strSQL)
If rs.RecordCount = 0 Then ' not in the personnel database
CmdAddToPersonnel.Enabled = True
Else
CmdAddToPersonnel.Enabled = False
End If
If Me![CmdSubmit].Visible = True Then
Me![CmdSubmit].Visible = False
Me![cmdCancel].Visible = False
End If
End Sub
Thanks

Maybe remove the semicolon and use Me.
strSQL = "SELECT PID from tblMSCSPersonnel WHERE SSN = '" & Me.TextSSN & "'"

Related

access vba sql-string with "'"

my second question for my baptisme app.
I made a form with two comboboxes to search the name en first name of a child.
The problem is when a ' character comes in the name I get an error. I think I understand why because in the sql-string the ' character is used.
I found this method for searching on the internet, but my knowledge of SQL is below zero. So I don't know what to do about it.
How can I do about this error??
Is there anyone who can help.
The error comes in the line: strSQL = "[Naam] = '" & Me.FComboNaam & "'". '(Naam = name)
The error can also arise in the line: strSQL = strSQL & " [voornaam] = '" & Me.FComboVoornaam & "'" '(Voornaam = first name). So far I don't know if there are first names with a ' in it.
I tried to resolve this problem with the instr function and delete the ' in the name, but this is not a solution because then the sql-string never find the name with the ' in it.
Here is my sub
Private Sub RequeryForm()
Dim strSQL As String
If Len("" & Me.FComboNaam) > 0 Then
strSQL = "[naam] = '" & Me.FComboNaam & "'"
End If
If Len("" & Me.FComboVoornaam) > 0 Then
If Len(strSQL) > 0 Then
strSQL = strSQL & " And "
End If
strSQL = strSQL & " [voornaam] = '" & Me.FComboVoornaam & "'"
End If
If Len(strSQL) = 0 Then 'als de filter leeg is deze afzetten
Me.FilterOn = False
Else
Me.filter = strSQL 'als de filter niet leeg is deze aanzetten
Me.FilterOn = True
End If
End Sub
I search the internet and found the instr function but that doesn't help.
I want to know if I can avoid this error one way or an other.
The error I get is error 3075 during execution. syntax error. Operator is missing in query expression [Naam] = 'D'Hondt'
My SQL-string is not the problem, but the name with a ' in it: D'Hondt (=name)
How can I find a name like D'Hondt

editing all fields in an access row based off of primary key

My work uses a userform in excel as the front end module for an Access database. I want to make it possible to edit ALL fields in a purchase order based off of the unique transaction ID (primary key) in that database. So far, the code I use seems to randomly update some records and not others without giving any errors. the Access db is a .mdb file (2003). I am wondering if there is a command to move from field to field during edit, but can't seem to come up with a reason for why you would need it??
``
Sub EDIT_PO()
On Error GoTo ErrorHandler
Application.EnableCancelKey = xlDisabled
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim nConnection As New ADODB.Connection
Dim nRecordset As New ADODB.Recordset
Dim sqlQuery As String
'Connection Strings - Dynamic Path
#If Win64 Then
nConnection.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "C:\Users\samue\OneDrive\Desktop\Database1.mdb"
#Else
nConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & "C:\Users\samue\OneDrive\Desktop\Database1.mdb"
#End If
sqlQuery = "Select * from PO_TABLE"
'Open the recordset
nRecordset.Open Source:=sqlQuery, ActiveConnection:=nConnection, CursorType:=adOpenKeyset, LockType:=adLockOptimistic
If nRecordset.Fields("Transaction ID").Value = CStr(POform.poformtransid.Value) Then
With nRecordset
.Fields("PO Number").Value = POform.poformponumber.Value
.Fields("PO Date").Value = CDate(POform.poformpodate.Value)
.Fields("Status").Value = POform.poformstatus.Value
.Fields("Material ID").Value = POform.poformmatid.Value
.Fields("Unit Cost").Value = CDbl(POform.poformunitcost.Value)
.Fields("QTY").Value = CDbl(POform.poformamount.Value)
.Fields("QTY Units").Value = POform.poformunits.Value
.Fields("Vendor ID").Value = POform.poformvendorid.Value
.Fields("Receipt Date").Value = CDate(POform.poformreceiptdate.Value)
.Fields("Supporting File").Value = POform.poformsf1.Value
.Fields("Lot Identifier").Value = POform.poformlotinfo.Value
.Update
.Close
End With
End If
nRecordset.Close
nConnection.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Exit Sub
ErrorHandler:
MsgBox Err.Description & " " & Err.Number, vbOKOnly + vbCritical, "Database Error"
Application.DisplayAlerts = True
Application.ScreenUpdating = True
nConnection.Close
End Sub
``
You just open table, so any record may be the first. Try filtering for the specific record you wish to edit:
sqlQuery = "Select * from PO_TABLE Where [Transaction ID] = '" & CStr(POform.poformtransid.Value) & "'"
or, if the ID is numeric:
sqlQuery = "Select * from PO_TABLE Where [Transaction ID] = " & CStr(POform.poformtransid.Value) & ""

Difficulty using SELECT statement in VBA

I'm trying to set command buttons to enter data into a table. If the record already exists I want the button to update it, and if it does not the button needs to create it. Here's a sample of what the table looks like
ID scenarioID reductionID Impact Variable Variable Impact
1 1 1 Safety 4
2 1 1 Environmental 2
3 1 1 Financial 1
In order to accurately locate records, it needs to search for the specific impact variable paired with the scenarioID. I'm trying to use a select statement, but DoCmd.RunSQL doesn't work for select statements, and I'm not sure how else to do it.
Here's the code. I left DoCmd.SQL in front of the select statement for lack of anything else to place there for now.
Private Sub Var1R1_Click() 'Stores appropriate values in tImpact upon click
'Declaring database and setting recordset
Dim db As Database
Dim rs As Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("tImpact")
'Declaring Variable as Scenario Choice combobox value
Dim Sc As Integer
Sc = Schoice.Value
'Stores impact variable
Dim impvar1 As String
'Desired impact variable for column 1
impvar1 = DLookup("impactVariable", "tImpactVars", "ID = 1")
DoCmd.RunSQL "SELECT * FROM tImpact WHERE [Impact Variable] = " & impvar1 & " AND scenarioID = " & Sc
If rs.EOF Then
DoCmd.RunSQL "INSERT INTO tImpact(scenarioID, [Impact Variable], [Variable Impact])" & "VALUES (" & Sc & ", " & impvar1 & ", 1)"
MsgBox "Record Added", vbOKOnly
Else
db.Execute "UPDATE tImpact SET [Variable Impact] = 1 WHERE [Impact Variable] = " & impvar1 & " AND scenarioID = " & Sc
MsgBox "Record Updated", vbOKOnly
End If
End Sub
If anyone can tell me how to get that SELECT statement to run, or another way of doing this, that would be great.
Any help is greatly appreciated!
You can use a recordset. In this case a recordset is better, since you only execute the SQL one time, if it returns a record, you "edit" and if not then you "add" with the SAME reocrdset. This approach is FAR less code, and the values you set into the reocrdset does not require messy quotes or delimiters etc.
eg:
scenaridID = 1 ' set this to any number
impvar1 = "Safety" ' set this to any string
updateTo = "Financial"
strSQL = "select * from tImpact where [Impact Variable] = '" & impvar1 & "'" & _
" AND scenaridID = " & scenaridID
Set rst = CurrentDb.OpenRecordset(strSQL)
With rst
If .RecordCount = 0 Then
' add the reocrd
.AddNew
Else
.Edit
End If
!scenaridID = scenarid
![Impact Variable] = impvar1
![Variable Impact] = 1
.Update
End With
rst.Close
So you can use the same code for the update and the edit. It just a question if you add or edit.
Use OpenRecordset and retrieve the ID for the record if it exists.
Private Sub Command0_Click()
Dim aLookup(1 To 3) As String
Dim aAction(1 To 3) As String
Dim rs As Recordset
Dim db As Database
'Replace these two constants with where you get the information on your form
Const sIMPVAR As String = "Financial"
Const lSCENID As Long = 1
'Build the SQL to find the ID if it exists
aLookup(1) = "SELECT ID FROM tImpact"
aLookup(2) = "WHERE ScenarioID = " & lSCENID
aLookup(3) = "AND ImpactVariable = """ & sIMPVAR & """"
'Run the sql to find the id
Set db = CurrentDb
Set rs = db.OpenRecordset(Join(aLookup, Space(1)))
If rs.BOF And rs.EOF Then 'it doesn't exist, so build the insert statement
aAction(1) = "INSERT INTO tImpact"
aAction(2) = "(ScenarioID, ImpactVariable, VariableImpact)"
aAction(3) = "VALUES (" & lSCENID & ", '" & sIMPVAR & "', 1)"
Else 'it does exist, so build the update statement
aAction(1) = "UPDATE tImpact"
aAction(2) = "SET VariableImpact = 1"
aAction(3) = "WHERE ID = " & rs.Fields(0).Value
End If
'Run the action query
db.Execute Join(aAction, Space(1))
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub

VBA Teradata SQL

For some reason it's returning run-time error 3021 , SQL string is working ok when trying in Terada SQLAssistant.
Can someone give me hint what I'm doing wrong ?
Value in cell equal to John Doe
Dim ConcatSQL As String
ConcatSQL = Sheets("LogIn").Cells(8, 3).Value
QueryA = "select * from database.table WHERE Name = " & ConcatSQL & "
cmdSQLData.CommandText = QueryA
cmdSQLData.CommandType = adCmdText
cmdSQLData.CommandTimeout = 0
MsgBox (QueryA)
Set rs = cmdSQLData.Execute()
Row = 1
rs.MoveFirst ' it's falling here
Do While (rs.EOF = False And rs.BOF = False)
One possible reason for the error is that field Name is a reserved word in Teradata, so you should use "Name" (using double quotes) instead
QueryA = "select * from database.table WHERE " & Chr(34) & "Name" & Chr(34) & " = " & ConcatSQL
Could you try this:
On Error Resume Next
Set rs = cmdSQLData.Execute()
If Err.Number<>0 Then
MsgBox(Err.Description)
End If
And post the output? Also can you post the output of QueryA.

MS Access VBA IF()

I am trying to write an if loop for MS Access VBA
In php I would write:
if($query=="0"){
run query 1
} else {
run query 2
}
I do need to call the query in and refer to multiple tables (ie. 'query 1' will extract data from a combo box, whereas, 'query 2' will run another query)
------------------------------------EDIT: 02/06/14 13:34 AEST ----------------------------
Dim variabl1 As String
variabl1 = Me.cmbItemDetails.Column(1)
Dim variabl2 As String
variabl2 = "" & Forms!frmRaiseOrder!cmbDebtorCode & ""
'you can use variable as a parameter in SQL, but only if you hardcode your SQL statement as a string... See directly below
Dim SQL As String
SQL_count = "SELECT COUNT(CustItemPrice) FROM tblSpecialPricing WHERE ItemListID = '" & variabl1 & "' AND CustListID = '" & variabl2 & "' "
SQL_select = "SELECT CustItemPrice FROM tblSpecialPricing WHERE ItemListID = '" & variabl1 & "' AND CustListID = '" & variabl2 & "' "
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset(SQL_count)
If rs.RecordCount = "0" Then
Me.txtStreetPrice.Value = Me.cmbItemDetails.Column(3)
Else
DoCmd.OpenQuery "qrySelectCustomerName"
End If
Thanks to #MurDeR for the assistance for the above statements
----------------------------------------------- Update as of 9th July -----------------------------------
Hi everyone;
If you are trying to create an IF() statement in ACCESS VBA, use the following syntax...
Private Sub cmbItemDetails_Change()
Me.txtItemDescription.Value = Me.cmbItemDetails.Column(2)
Me.txtStreetPrice.Value = Me.cmbItemDetails.Column(3)
Me.txtItemName.Value = Me.cmbItemDetails.Column(1)
Dim variabl1 As String
variabl1 = Me.cmbItemDetails.Column(0)
Dim variabl2 As String
variabl2 = "" & Forms!frmRaiseOrder!cmbDebtorCode & ""
'you can use variable as a parameter in SQL, but only if you hardcode your SQL statement as a string... See directly below
Dim SQL As String
SQL_count = "SELECT COUNT(CustItemPrice) FROM tblSpecialPricing WHERE ItemListID = '" & variabl1 & "' AND CustListID = '" & variabl2 & "' "
SQL_select = "SELECT CustItemPrice FROM tblSpecialPricing WHERE ItemListID = '" & variabl1 & "' AND CustListID = '" & variabl2 & "' "
Dim rs As Recordset
Set rs = Nothing
Set rs = CurrentDb.OpenRecordset(SQL_count)
RecordCount = rs.Fields(0)
If RecordCount = "1" Then
'SPECIAL PRICE EXISTS - this code will run only if the count query is greater than zero
MsgBox "Special Price Exists", vbOkay, "Alert"
'
'
Me.txtUnitPrice.Value = Me.cmbItemDetails.Column(3)
'Me.txtUnitPrice.Value = "" & Forms!frmRaiseOrder!subformCreateOrder!frmSelectCustomPriceinsubform!CustItemPrice & ""
'Me.txtUnitPrice.Value = Me.subfrmItemPrice.CustItemPrice.Value
Else
'NO SPECIAL PRICE - this code will run only if the coutn query is zero
'MsgBox "No Special Pricing for this item", vbOkay, "Alert"
'
'
Me.txtUnitPrice.Value = Me.cmbItemDetails.Column(3)
End If
End Sub
I would really like to thank and credit #MurDeR for their help and also if you have any questions, PM me or post here
You can work with a recordset in VBA.
See this bit of code for a start.
Dim variabl As String
variabl = Me.ComboBox1.Value
'you can use variabl as a parameter in SQL, but only if you hardcode your SQL statement as a string... See directly below
Dim SQL As String
SQL = "SELECT * FROM TableA WHERE YourColumnName = '" & variabl & "'"
Dim db As DAO.Database
db = CurrentDb
Dim rs As DAO.Recordset
Set rs = db.OpenRecordset("SQL Statement or Query Name")
If rs.RecordCount = 0 Then
DoCmd.OpenQuery "Query1"
Else
DoCmd.OpenQuery "Query2"
End If
rs.Close
Set rs = Nothing
Let me know if you have any other questions. Also note, you need to make sure you're entering proper query names. I know VBA has pathetic intellisense, so this can be tricky when entering query names as strings.