I am trying to create a search form in MS Access 2013, each time i insert the search criteria in any of the fields created i get the error message
"syntax error (missing operator) in query expression "*FROMWHERE (FirstName) like "Godswill""AND"
find below the codes
<blink>
Private Sub cmdSearch_Click()
On Error GoTo errr
Me.qryCandInfo_subform.Form.RecordSource = "SELECT*FROM" & BuildFilter
Me.qryCandInfo_subform.Requery
Exit Sub
errr:
MsgBox Err.Description
End Sub
Private Function BuildFilter() As Variant
Dim varWhere As Variant
Dim tmp As String
tmp = """"
Const conSetDate = "\#dd\/mm\/yyyy\#"
varWhere = Null
If Me.txtEnrNo > "" Then
varWhere = varWhere & "(Enr_No) like " & Me.txtEnrNo & "AND"
End If
If Me.txtFirstName > "" Then
varWhere = varWhere & "(First_Name) like " & tmp & Me.txtFirstName & tmp & "AND"
End If
If Me.txtDateFrom > "" Then
varWhere = varWhere & "((Admisssion_Year)>= " & Format(Me.txtDateFrom, conSetDate) & ") AND"
End If
If Me.txtDateTo > "" Then
varWhere = varWhere & "((Admisssion_Year)<= " & Format(Me.txtDateTo, conSetDate) & ") AND"
End If
If IsNull(varWhere) Then
varWhere = ""
Else
varWhere = "WHERE" & varWhere
If Right(varWhere, 5) = "AND" Then
varWhere = Left(varWhere, Len(varWhere) - 5)
End If
End If
BuildFilter = varWhere
End Function
There is a lot wrong with your code.
To make it easy for you and everybody involved: Add spaces before and after every keyword:
"SELECT*FROM" & BuildFilter => "SELECT * FROM " & BuildFilter
& "AND" => & " AND "
varWhere = "WHERE" & varWhere => varWhere = " WHERE " & varWhere
& ") AND" => & ") AND "
Additionally you are missing to specfify the table you want to select from...
Furthermore your SQL has a trailing AND. Either take care of that or choose the not so perfect approch of appening a 1: varWhere = " WHERE " & varWhere & " 1". (Your version checks for ending with some 5 characters and compare with And - that should NEVER be true...)
Furthermore: SQL-injection... I doubt that pre- and appening """" changes anything
Related
I have a report that uses the following SQL query:
SELECT AccountPerformanceAllHistory.AccountNumber,
AccountMaster.AccountName AS Name, AccountCurrentModel.Model,
AccountPerformanceAllHistory.MarketValue,
AccountPerformanceAllHistory.Cash, ModelDetailAllHistory.Risk,
AccountPerformanceAllHistory.QTD, AccountPerformanceAllHistory.YTD,
AccountPerformanceAllHistory.[1Yr], AccountPerformanceAllHistory.[3Yr],
AccountMaster.AccountAdvisor AS Advisor,
AccountPerformanceAllHistory.PerformanceDate,
AccountPerformanceAllHistory.Ticker
FROM ModelDetailAllHistory INNER JOIN ((AccountMaster INNER JOIN
AccountPerformanceAllHistory ON AccountMaster.[AccountNumber] =
AccountPerformanceAllHistory.[AccountNumber]) INNER JOIN
AccountCurrentModel ON AccountMaster.[AccountNumber] = AccountCurrentModel.
[AccountNumber]) ON ModelDetailAllHistory.[ModelName] =
AccountCurrentModel.Model
GROUP BY AccountPerformanceAllHistory.AccountNumber,
AccountMaster.AccountName, AccountCurrentModel.Model,
AccountPerformanceAllHistory.MarketValue,
AccountPerformanceAllHistory.Cash, ModelDetailAllHistory.Risk,
AccountPerformanceAllHistory.QTD, AccountPerformanceAllHistory.YTD,
AccountPerformanceAllHistory.[1Yr], AccountPerformanceAllHistory.[3Yr],
AccountMaster.AccountAdvisor, AccountPerformanceAllHistory.PerformanceDate,
AccountPerformanceAllHistory.Ticker
ORDER BY ModelDetailAllHistory.Risk, AccountPerformanceAllHistory.[1Yr]
DESC;
The report is run from a button-click:
Private Sub Command3_Click()
Dim StrWhichMonth As String
Dim StrWhichClient As String
Dim CYear, CMonth As Variant
Dim StrSearch As String
StrWhichMonth = InputBox("Enter YYMM you want to report:")
CYear = "20" & Mid(StrWhichMonth, 1, 2)
CMonth = Mid(StrWhichMonth, 3, 2)
StrWhichMonth = DateSerial(CYear, CMonth + 1, 0)
StrWhichClient = InputBox("Enter Client name ('*' for all):")
StrSearch = "AccountPerformanceAllHistory.PerformanceDate = #" & StrWhichMonth _
& "# AND AccountPerformanceAllHistory.Ticker = " & Chr(34) & "1" & Chr(34) & "" _
& " AND AccountMaster.AccountName Like " & Chr(34) & StrWhichClient & Chr(34)
StrWhichMonth = "AccountPerformanceAllHistory.PerformanceDate = #" & StrWhichMonth _
& "# AND AccountPerformanceAllHistory.Ticker = " & Chr(34) & "1" & Chr(34) & ""
DoCmd.SetWarnings False
' DoCmd.OpenReport "RPTAccountPerformanceAllHistorySummary", acViewReport, , StrWhichMonth
DoCmd.OpenReport "RPTAccountPerformanceAllHistorySummary", acViewReport, , StrSearch
DoCmd.SetWarnings True
End Sub
As you might can tell, I added the search for AccountName in the button click code. The old code works fine.
The new code, with the StrSearch string does not work. When the query is run, it prompts for "AccountMaster.AccountName" after the two InputBox prompts. I know this means something is wrong with the StrSearch, but I don't know what is wrong. I've searched around the web, but could not find a solution.
Any help is appreciated.
TIA
The field list in your source query includes this one ...
AccountMaster.AccountName AS Name
Since you aliased the field, the query result set does not include a field named AccountMaster.AccountName, so Access assumes it must be a parameter and asks you to supply a value for it. Use the alias instead instead of the original field name.
Change this ...
& " AND AccountMaster.AccountName Like " & Chr(34) & StrWhichClient & Chr(34)
to this ...
& " AND [Name] Like " & Chr(34) & StrWhichClient & Chr(34)
Teller = Nz(DLookup("[Teller]", "[Lookuptable]", ("Artikel = '" & ValueArtikel & "' " And " Lookuptable= 'G'")), 0)
Noemer = Nz(DLookup("[Noemer]", "[lookuptable]", ("Artikel = ' " & ValueArtikel & " ' " And Lookuptable= " 'G' ")), 0)
I want to perform a DLOOKUP in acces vba but i can't find the right statement. I looked at many sites and this are the two dlookups that i think are correct but both give the error types don't match. Teller and noemer are integers, Artikel and artikelvalue and Lookuptable are strings. Sorry if this is already asked but i can't find it. i find many posts about it but i can't fixed it. And especcialy sorry for my bad english
The first one is close. Use variables and Debug.Print to help building the strings.
Ctrl+g shows the output.
strCrit = "Artikel = '" & ValueArtikel & "' And Lookuptable= 'G'"
Debug.Print strCrit
Teller = Nz(DLookup("[Teller]", "[Lookuptable]", strCrit), 0)
I use my own function for Lookups because Lookups have a really bad performance.
' Lookups Replacements
'---------------------
Function DLook(Expression As String, Domain As String, Optional Criteria) As Variant
On Error GoTo Err_Handler
Dim strSQL As String
'DCount: strSQL = "SELECT COUNT(" & Expression & ") FROM " & Domain
'Other replacements
'DLookup:
strSQL = "SELECT " & Expression & " FROM " & Domain
'DMax: strSQL = "SELECT MAX(" & Expression & ") FROM " & Domain
'DMin: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DFirst: strSQL = "SELECT FIRST(" & Expression & ") FROM " & Domain
'DLast: strSQL = "SELECT LAST(" & Expression & ") FROM " & Domain
'DSum: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DAvg: strSQL = "SELECT AVG(" & Expression & ") FROM " & Domain
If Not IsMissing(Criteria) Then strSQL = strSQL & " WHERE " & Criteria
DLook = DBEngine(0)(0).OpenRecordset(strSQL, dbOpenForwardOnly)(0)
Exit Function
Err_Handler:
MsgBox "Error. Lookup couldnt be performed" & vbNewLine & Err.Description, vbCritical
End Function
Called with:
If DLook("Column2", "Table1", "Column1 = " & ID) = 0 Then
'Do stuff
End If
If DLook("Column2", "Table1") = 0 Then
'Do other stuff
End If
I have 8 combo boxes in an Access database. Each combo box can either have a value or not have a value (2 options). In total, there can be 256 combinations (2^8). I am trying to create some code in VBA that loops through these combinations to determine which combination currently exists, with the ultimate goal of writing an SQL query within VBA based on that combination. So for example, let's say combo1 and combo2 both have selections, but not combo3 through combo8. If that is the combination I would like my SQL query to do a SELECT FROM query WHERE a column in db = combo1 and a column in db = combo2. Can anyone provide hints as to how I would structure my code?
Thanks!
Dim a as string, b as string
const myAND as string = "AND "
a = ""
a = "SELECT * FROM a table "
b = ""
if cbo1.value <> "" then
b = b & myAND & "AND field1 = '" & cbo1.value & "'"
end if
if cbo2.value <> "" then
b = b & myAND & "field2 = '" & cbo2.value & "'"
end if
etc for each cbo box
If b <> "" Then
' Lazy way
' a = a & "WHERE 1=1 " & b
' remove the first AND way
a = a & "WHERE 1=1 " & mid(b,len(myAND))
End if
' a now contains the SQL you need.
Dim where_condtion as String
Dim sqlquery as String
where_condtion = ""
IF combo1 <>"" then
where_condtion = where_condtion + "~fieldname~ = " & combo1
End IF
IF combo2 <>"" then
where_condtion = where_condtion + "AND ~fieldname~ = " & combo2
End IF
*
*
*
IF combo8 <>"" then
where_condtion = where_condtion + "AND ~fieldname~ =" & combo8
End IF
IF where_condtion <> "" then
sqlquery = "Select * from ~table name~ where" + where_condtion
ELSE
sqlquery = "Select * from ~table name~
End IF
sqlquery = Replace(sqlquery, "where AND ", "where ")
DoCmd.OpenQuery "sqlquery", acViewNormal, acEdit
OR
CurrentDb.OpenRecordset("sqlquery")
Am option would be a concatenated string
Code Example
Dim strSQL as String
'basic string
strSQL = "SELECT tbl.fieldA, tbl.fieldB FROM tbl "
Dim strSQLwhere as String
strSQLwhere = ""
'Combobox cmbbox1
If Not isNull(cmbbox1) And cmbbox1.ListIndex <> -1 then
strSQLwhere = strSQLwhere & "tbl.fieldToFilter1=" & cmbbox1
End if
'Combobox cmbbox2
If Not isNull(cmbbox2) And cmbbox2.ListIndex <> -1 then
iF NOT strSQLwhere = "" then
strSQLwhere = strSQLwhere & " AND "
end if
strSQLwhere = strSQLwhere & "tbl.fieldToFilter2=" & cmbbox2
End if
'And so on until cmbBox 8
'Combine all Strings
if not strSQLwhere = "" then
strSQL = strSQL & " WHERE (" & strSQLwhere & ")"
End if
'Add here further thing like ORDER BY, GROUP BY
'Show SQL sting if it is well fomratted, change string concatenation if not
debug.print strSQL
You could do the combobox if-then-(else) cases in a separate function if you are able to do that in VBA.
I'm trying to delete all the records of one table that appear in another, however it only seems to delete some of the records.
Private Sub removeDuplicates()
Dim resultSet1 As DAO.Recordset
Set resultSet1 = CurrentDb.OpenRecordset("remove")
resultSet1.MoveFirst
Do Until resultSet1.EOF
Dim sql As String
sql = "Delete * from [Copy Of remove] Where"
If Not IsNull(resultSet1.Fields(0)) And (resultSet1.Fields(0) <> "") Then
sql = sql & " PHN = """ & resultSet1.Fields("PHN") & """"
End If
If Not IsNull(resultSet1.Fields(1)) And (resultSet1.Fields(1) <> "") Then
sql = sql & " and Year = " & resultSet1.Fields(1)
End If
If Not IsNull(resultSet1.Fields(2)) And (resultSet1.Fields(2) <> "") Then
sql = sql & " and [Date of Referral to Thoracics] = " & resultSet1.Fields(2)
End If
If Not IsNull(resultSet1.Fields(3)) And (resultSet1.Fields(3) <> "") Then
sql = sql & " and [Date of Thoracics Consult] = " & resultSet1.Fields(3)
End If
If Not IsNull(resultSet1.Fields(4)) And (resultSet1.Fields(4) <> "") Then
sql = sql & " and [Date Thoracic Surgery Booked] = " & resultSet1.Fields(4)
End If
If Not IsNull(resultSet1.Fields(5)) And (resultSet1.Fields(5) <> "") Then
sql = sql & " and [Date of Thoracic Surgery] = " & resultSet1.Fields(5)
End If
If Not IsNull(resultSet1.Fields(6)) And (resultSet1.Fields(6) <> "") Then
sql = sql & " and [Study Group] = """ & resultSet1.Fields(6) & """"
End If
If Not IsNull(resultSet1.Fields(7)) And (resultSet1.Fields(7) <> "") Then
sql = sql & " and [Access Method] = """ & resultSet1.Fields(7) & """"
End If
If Not IsNull(resultSet1.Fields(8)) And (resultSet1.Fields(8) <> "") Then
sql = sql & " and Procedure = """ & resultSet1.Fields(8) & """"
End If
If Not IsNull(resultSet1.Fields(9)) And (resultSet1.Fields(9) <> "") Then
sql = sql & " and Site = """ & resultSet1.Fields(9) & """"
End If
If Not IsNull(resultSet1.Fields(10)) And (resultSet1.Fields(10) <> "") Then
sql = sql & " and [Procedure 2] = """ & resultSet1.Fields(10) & """"
End If
If Not IsNull(resultSet1.Fields(11)) And (resultSet1.Fields(11) <> "") Then
sql = sql & " and [Site 2] = """ & resultSet1.Fields(11) & """"
End If
If Not IsNull(resultSet1.Fields(12)) And (resultSet1.Fields(12) <> "") Then
sql = sql & " and [Primary site] = """ & resultSet1.Fields(12) & """"
End If
If Not IsNull(resultSet1.Fields(13)) And (resultSet1.Fields(13) <> "") Then
sql = sql & " and Grade = """ & resultSet1.Fields(13) & """"
End If
If Not IsNull(resultSet1.Fields(14)) And (resultSet1.Fields(14) <> "") Then
sql = sql & " and [T Stage] = """ & resultSet1.Fields(14) & """"
End If
If Not IsNull(resultSet1.Fields(15)) And (resultSet1.Fields(15) <> "") Then
sql = sql & " and [N Stage] = """ & resultSet1.Fields(15) & """"
End If
If Not IsNull(resultSet1.Fields(16)) And (resultSet1.Fields(16) <> "") Then
sql = sql & " and [M Stage] = """ & resultSet1.Fields(16) & """"
End If
If Not IsNull(resultSet1.Fields(17)) And (resultSet1.Fields(17) <> "") Then
sql = sql & " and [Same Staging?] = """ & resultSet1.Fields(17) & """"
End If
CurrentDb.Execute sql
resultSet1.MoveNext
Loop
resultSet1.Close
End Sub
This is the code I'm using, to test if it works I've been using the table remove and Copy Of Remove but only about 20 of the 135 records are being deleted even though one is a copy of the other.
Also I match all fields when creating the delete query and I have a feeling this is where the issue is coming from.
P.S.
Option explicit and option compare database are declared above this sub
You haven't quoted your date value, so you're doing a division operation:
DELETE ... WHERE [Date...] = 6/5/2013
which becomes
DELETE ... WHERE [Date...] = 0.0005961etc...
Try
DELETE ... WHERE [Date...] = #6/5/2013#
^--------^
instead.
I want to update serial.Issuedate getting from form but its giving syntax error.
Please help me how can I correct this error.
My code is below:
Private Sub Command30_Click()
Set serialrs = CurrentDb.OpenRecordset("serial")
Dim Idate As Date
Dim Itodo As String
Idate = Me.IssuedDate.Value
Itodo = Me.IssuedToDO.Value
Dim issueqry As String
issueqry = "UPDATE serial " _
& " set serial.IssueToDO = '" & Itodo & "'" _
& " serial.issuedate = (#" & Format(Idate, "mm\/dd\/yyyy") & "#)" _
& " WHERE (((serial.id) Between 1 And 10)) "
DoCmd.RunSQL issueqry
MsgBox ("Issued Done")
End Sub
When you update more than one field, you must include a comma between the field expressions like this ...
SET [field name] = "foo", [another field] = 17
^
here
So try your code like this ...
issueqry = "UPDATE serial " _
& " set serial.IssueToDO = '" & Itodo & "'," _
& " serial.issuedate = #" & Format(Idate, "mm/dd/yyyy") & "#" _
& " WHERE serial.id Between 1 And 10"
Also give yourself an opportunity to inspect the string the code built ...
Debug.Print issueqry
You can view the output from Debug.Print in the Immediate window. Ctrl+g will take you there.