This is my code below. I am trying to search a database using two different dates, company name
I am getting an error when one of the date fields is empty or null. How can I solve this issue or bypass if the date search field is empty to ignore it in the search or search for an empty field?
Dim SQL As String
SQL = "SELECT * from qryRequestInternal where ([DateRequestSent] = #" & txt_Search_Sdate & "# AND [DateReceived] = #" & txt_Search_Rdate & "# AND (companyName like ""*" & txt_SCompNa & "*"") )"
Me.sfrmRequestInternal.Form.RecordSource = SQL
Me.sfrmRequestInternal.Form.Requery
Me.sfrmRequestInternal_col.Form.RecordSource = SQL
Me.sfrmRequestInternal_col.Form.Requery
End Sub
You will need to check for Null values and build the SQL string based on the controls which have a value (i.e. not null).
The example below uses a helper function to build the sql string. If nothing is inserted, it will only run the the Select * from qryRequestInternal without any criteria.
Private Function SqlWhere() As String
Dim retvalue As String
'sent date
With txt_Search_Sdate
If Not IsNull(.Value) Then
retvalue = " WHERE [DateRequestSent] = #" & Format(.Value, "mm/dd/yyyy") & "#"
End If
End With
'received date
With txt_Search_Rdate
If Not IsNull(.Value) Then
retvalue = IIf(Len(retvalue) = 0, " WHERE", retvalue & " AND") & " [DateReceived] = #" & Format(.Value, "mm/dd/yyyy") & "#"
End If
End With
'company
With txt_SCompNa
If Not IsNull(.Value) Then
retvalue = IIf(Len(retvalue) = 0, " WHERE", retvalue & " AND") & " [companyName] Like '*" & .Value & "*'"
End If
End With
SqlWhere = retvalue
End Function
To call it:
Dim sqlString As String
sqlString = "SELECT * from qryRequestInternal" & SqlWhere()
Debug.Print sqlString
Im trying to create a VBA sql string with the where clause using inputs from an access form. I need the code to still run properly even if one of the user inputs is null/unselected. The code below runs correctly when all user inputs have been selected but when one input is null/unselected the query ends up pulling back all the records in the table.
Dim SQL As String
SQL = "SELECT qry_1.field1, qry_1.field2, qry_1.field3 INTO recordset FROM qry_1" & _
" WHERE ((qry_1.Field1) IS NULL OR (qry_1.Field1) = '" & [Forms]![frm_Parameters]![cmbx_1] & "') " &_
" AND ((qry_1.Field2) IS NULL OR (qry_1.Field2) = '" & [Forms]![frm_Parameters]![cmbx_2] & "' ) " & _
" AND ((qry_1.Field3) IS NULL OR (qry_1.Field3) = '" & [Forms]![frm_Parameters]![cmbx_3] & "') ;"
DoCmd.RunSQL SQL
It is better to escape single apostrophes in the text for two reasons
You might get an invalid SQL statement if you don't.
A nasty user could can inject evil code (see: SQL injection).
Therefore I use this function
Public Function SqlStr(ByVal s As String) As String
'Input: s="" Returns: NULL
'Input: s="abc" Returns: 'abc'
'Input: s="x'y" Returns: 'x''y'
If s = "" Then
SqlStr = "NULL"
Else
SqlStr = "'" & Replace(s, "'", "''") & "'"
End If
End Function
To account for empty entries, create the condition like this:
Dim cond As String, sql As String
If Nz([Forms]![frm_Parameters]![cmbx_1]) <> "" Then
cond = "qry_1.field1 = " & SqlStr(Nz([Forms]![frm_Parameters]![cmbx_1]))
End If
If Nz([Forms]![frm_Parameters]![cmbx_2]) <> "" Then
If cond <> "" Then cond = cond & " AND "
cond = cond & "qry_1.field2 = " & SqlStr(Nz([Forms]![frm_Parameters]![cmbx_2]))
End If
If Nz([Forms]![frm_Parameters]![cmbx_3]) <> "" Then
If cond <> "" Then cond = cond & " AND "
cond = cond & "qry_1.field3 = " & SqlStr(Nz([Forms]![frm_Parameters]![cmbx_3]))
End If
sql = "SELECT qry_1.field1, qry_1.field2, qry_1.field3 INTO recordset FROM qry_1"
If cond <> "" Then
sql = sql & " WHERE " & cond
End If
This assumes that you want to test a condition only when the corresponding field is not empty.
If you have date constants, format them the Access-SQL way as #2018-08-21# with
Format$(date, "\#yyyy-MM-dd\#")
DoCmd.RunSQL is for action queries (UPDATE, INSERT, DELETE).
To answer the question, here is what I would do:
Nz(Field1,Nz([Forms]![frm_Parameters]![cmbx_1]))=Nz([Forms]![frm_Parameters]![cmbx_1])
That will create equality if either Field1 or [Forms]![frm_Parameters]![cmbx_1] is NULL without breaking the rest of the query.
To use that in VBA:
"Nz(Field1,'" & Nz([Forms]![frm_Parameters]![cmbx_1]) & "')='" & Nz([Forms]![frm_Parameters]![cmbx_1]) & "'"
Also see comment in Olivier Jacot-Descombes answer about taking single quotes in your strings into account.
I am creating a form on Access to filter a Subform based on the Column name "Control Type".
I am using a listbox to choose multiple values to filter with.
I also have a button that will execute the filter to the form.
I wrote this code:
Private Sub cmdSearch_Click()
Dim varItem As Variant
Dim strSearch As String
Dim Task As String
For Each varItem In Me!listControl.ItemsSelected
strSearch = strSearch & "," & Me!listControl.ItemData(varItem)
Next varItem
If Len(strSearch) = 0 Then
Task = "select * from tblAB"
Else
strSearch = Right(strSearch, Len(strSearch) - 1)
Task = "select * from tblAB where Control_Type = '" & strSearch & "' "
End If
Me.tblAB_subform.Form.Filter = Task
Me.tblAB_subform.Form.FilterOn = True
End Sub
I am getting a Run=time error '3075' for the line:
Task = "select * from tblAB where Control_Type = '" & strSearch & "' "
Run time error must not be on refered line.
From documentation:
The Filter property is a string expression consisting of a WHERE
clause without the WHERE keyword.
So is not a complete SELECT sentence, but just:
Task = "Control_Type = '" & strSearch & "'"
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
My goal is to return the results of 5 textboxes into a SQL query, by incorporating the Query string with the variables.
How can I get my code to function so that when a checkbox is checked, the value (eg: ID, SC...) is recorded and placed into a Query? And if a checkbox is not checked, then it is not placed into the query.
The 5 checkboxes are as follows:
The code I current have to record whether a textbox is selected, and to place the value (eg: ID, SC, AS...) into a variable is as follows:
If (Me.BoxID = False) And (Me.BoxSC = False) And (Me.BoxASSC = False) And (Me.BoxAS = False) And (Me.BoxEH = False) Then
MsgBox "You must check a Fonction Checkbox", 0
Exit Sub
Else
If (Me.BoxID= True) Then IDValue = Chr(34) & "ID" & Chr(34) Else IDValue = """"""
If (Me.BoxSC= True) Then SCValue = Chr(34) & "SC" & Chr(34) Else SCValue = """"""
If (Me.BoxASSC= True) Then ASSCValue = Chr(34) & "ASSC" & Chr(34) Else ASSCValue = """"""
If (Me.BoxAS= True) Then ASValue = Chr(34) & "AS" & Chr(34) Else ASValue = """"""
If (Me.BoxEH= True) Then EHValue = Chr(34) & "EH" & Chr(34) Else EHValue = """"""
End If
fonctionQryString = "(((tblF.f1)=" & IDValue & ") OR " + "((tblF.f1)=" & SCValue & ") OR " + "((tblF.f1)=" & ASSCValue & ") OR " + "(tblF.f1)=" & ASValue & ") OR " + "(tblF.f1)=" & EHValue & ")))"
The fonctionQryString goes into the WHERE section of the SQL Query.
I know that the method I'm using is not efficient, even though it works.
My problem is that I don't know how to do this another way. I want my code to function so that when a checkbox is not checked, it doesn't go into the Query string.
Any help would be much appreciated.
These two WHERE clauses should produce equivalent results. Consider switching to the second form.
WHERE tblF.f1 = "ID" OR tblF.f1 = "SC" OR tblF.f1 = "AS"
WHERE tblF.f1 IN ("ID","SC","AS")
Here is a rough and untested code sample to produce a similar WHERE clause based on my understanding of what you're trying to achieve.
Dim fonctionQryString As String
Dim lngLoopNum As Long
Dim strControlName As String
Dim strValueList As String
For lngLoopNum = 1 To 5
Select Case lngLoopNum
Case 1
strControlName = "ID"
Case 2
strControlName = "SC"
Case 3
strControlName = "ASSC"
Case 4
strControlName = "AS"
Case 5
strControlName = "EH"
End Select
If Me.Controls("Box" & strControlName) = True Then
strValueList = strValueList & "," & Chr(34) & _
strControlName & Chr(34)
End If
Next
If Len(strValueList) > 0 Then
fonctionQryString = "tblF.f1 IN (" & Mid(strValueList, 2) & ")"
Else
MsgBox "You must check a Fonction Checkbox"
End If
I assumed you didn't actually want to include the condition, WHERE tblF.f1 = "" (an empty string). If I guessed wrong, you'll have more work to do, but hopefully this will still point you to something useful.