VBA If textbox is empty display all values - vba

I have 2 textboxes and a button. The button opens a query with the values of the textboxes. Everything works fine, except when one textbox is empty then I want to find all the records from that textbox(So far I've tested it on textbox2). Here is my code:
Private Sub vbaBtn_Click()
Dim af1 As String, af2 As String
af1 = "([a1]='" + [krit1] + "') "
If krit2 = "" Then
af2 = "([a2]='" + "*" + "') "
Else
af2 = "([a2]='" + [krit2] + "') "
End If
DoCmd.OpenForm "FormLisategevusalad", acFormDS, , af1 & " " & "And" & " " & af2
End Sub
It seems to me, that VBA is always choosing the Else option not the If one, since when I debugged it said the error is an "Invalid use of null" and pointed to the Else condition.
Am I using a wrong method to detect and empty string? If I get the empty string recognition to work, is this af2 = "([a2]='" + "*" + "') " the right way to return all records?
Thanks in advance.

An empty textbox holds the value of Null, thus concatenating this with + results in a Null. Use &:
Private Sub vbaBtn_Click()
Dim af1 As String, af2 As String
af1 = "([a1]='" & [krit1] & "') "
If IsNull([krit2]) Then
af2 = "([a2] Is Not Null) "
Else
af2 = "([a2]='" & [krit2] & "') "
End If
DoCmd.OpenForm "FormLisategevusalad", acFormDS, ,af1 & " And " & af2
End Sub

Related

Search sql query when the number of where statements are variable

I haven't used access in a few years, but I am trying to create a search form where users can input search criteria in 8 different textboxes and then search based on how many boxes have data. Instead of trying to create a sql statement for every combination I have tried to create one sql statement that would work, but haven't found anything yet.
I have tried using a '*' for every blank textbox which did not work. I am using a variable for every column and thought I could use a empty string for the empty textbox columns but then I do not know which one would be the last and how to make the last variable not have an "AND" behind it. I could loop through the variables, but is there an easier way?
Here is my code as it is now...
Private Sub Command3_Click()
Dim frm As Form, rs As Recordset
Dim nb As String, cs As String, s As String, ss As String
Dim od As String, cd As String, t As String, tt As String, st As String
Dim sql_select As String, sql_from As String, sql_where As String
If IsNull(Me.txtNumb) Then nb = "" Else nb = "nc.[NC Number] = """ & Me.txtNumb & """"
If IsNull(Me.txtCS) Then cs = "" Else cs = "nc.[CS_Build] = """ & Me.txtCS & """"
If IsNull(Me.cbSection) Then s = "" Else s = "nc.[Section] = """ & Me.cbSection & """"
If IsNull(Me.cbSubSection) Then ss = "" Else ss = "nc.[Sub-Section] = """ & Me.cbSubSection & """"
If IsNull(Me.txtOpenDate) Then od = "" Else od = "nc.[Date_Open] = """ & Me.txtOpenDate & """"
If IsNull(Me.txtClosedDate) Then cd = "" Else cd = "nc.[Date_Closed] = """ & Me.txtClosedDate & """"
If IsNull(Me.cbTPS) Then t = "" Else t = "nc.[TPS] = """ & Me.cbTPS & """"
If IsNull(Me.cbTPStype) Then tt = "" Else tt = "nc.[TPS_Type] = """ & Me.cbTPStype & """"
If IsNull(Me.cbStatus) Then st = "" Else st = "nc.[Status] = """ & Me.cbStatus & """"
sql_select = "SELECT nc.[NC Number], nc.[Date_Open], nc.[CS_Build], nc.[Section], nc.[Sub-Section], nc.[Status], nc.[Date_Closed], nc.[Notes] "
sql_from = sql_query + "FROM nc "
sql_where = sql_query + "WHERE " & nb & " And " & od & " And " & cs & " And " & s & " And " & st & " And " & cd & " And " & ss & " And " & t & " And " & tt & ";"
Me.lstSearch.RowSource = sql_select + sql_from + sql_where
End Sub
I figured out a way to do this. I'm not sure it is a good way. I replaced the empty string "" when the textbox is empty with something that is always true like "1=1". That allowed the query to be executed.
But is there a better way?

Select Data from DataTable that are ISNUMERIC

I am trying to select data from DataTable using ISNUMERIC function, unfortunately I get error below:
System.Data.EvaluateException: "The expression contains the undefined
function call ISNUMERIC()."
this is my current code (sorry some parts are in German but to translate I don't think it makes sense)
Public dtFakturas As New DataTable
Artikelgruppe_Einfuegen(rows:=dtFakturas.Select("FAK_KundenNr = " & Adr_Nr &
" AND Liegenschaft = '" & Liegenschaft & "' " &
" AND Mandant = '" & Mandant & "' " &
" AND von = '" & VerrechnungsPeriode.Von & "'" &
" AND bis = '" & VerrechnungsPeriode.Bis & "'" &
" AND FAK_BoMatNr <> ''", "FAK_BoMatNr").Where(Function(r) IsNumeric(r("FAK_BoMatNr"))),
Postable:=PosTable,
Adr_Nr:=Adr_Nr,
Mandant:=Mandant,
Ueberschrift:="", MasterMandantConnectionString:=MastermandantConnectionString,
Verrechnen_bis:=VerrechnungsPeriode.Bis)
Private Function IsNumeric(ByVal o As Object) As Boolean
Dim result_ignored As Decimal
Return o IsNot Nothing AndAlso Not (TypeOf o Is DBNull) AndAlso Decimal.TryParse(Convert.ToString(o), result_ignored)
End Function
my question is: how do i correct a select query to function properly and only give me values that are ISNUMERIC?

Access dynamic filtering listbox with double where clause

I've got a dynamic textbox filtering function in VBA
Dim sSQL As String
sSQL = "SELECT qry_allUtilities.ID, qry_allUtilities.Supplier AS Lieferant, qry_allUtilities.Cabinet AS Ablageort, qry_allUtilities.Size AS Grösse, qry_allUtilities.WorkingLength AS Nutzlänge, qry_allUtilities.Description AS Bezeichnung "
sSQL = sSQL & " FROM qry_allUtilities "
If Not sFilter = "" Then
Dim arrFilter
arrFilter = Split(sFilter, "+")
Dim varWort
For Each varWort In arrFilter
If Not varWort = "" Then
Dim sWort As String
sWort = varWort
sSQL = sSQL & " AND [ID] & ' ' & [Supplier] & ' ' & [Floor] & ' ' & [Cabinet] & ' ' & [Size] & ' ' & [WorkingLength] LIKE '*" & sWort & "*'"
End If
Next
sSQL = Replace(sSQL, " AND ", " WHERE ", 1, 1, vbTextCompare)
End If
ctlListe.RowSource = sSQL
and would like to extend this with another WHERE clause because I have to exclude the records with qry_allUtilities.InActive=False
How do I do this? I always keep getting null or it won't exclude the records with InActive=True :/
I usually do this to add a variable (but unknown) number of filter options:
strFilter = "" ' build the filter string in here
if <first condition reason is true> then
strFilter = strFilter + first condition + " AND "
end if
if <second condition reason is true> then
strFilter = strFilter + <second condition> + " AND "
end if
' finish up
if len(strFilter) > 0 then ' some critera are valid
strFilter = Left(strFilter, Len(strFilter) - 5) ' chop off the spare " AND "
strFilter = " WHERE " + strFilter ' put the " WHERE " on the front
' else ' no where clause
end if
Note that the spaces either side of the " AND " and " WHERE " are important.

If Statement to change field.control source

I have a small If statement that that changes the controlsource of a field if another field is empty. The " just before = is incorrect, and I'm not sure what to use to ensure the entire string starting with the = is included.
Private Sub Report_Load()
If IsNull(FirstName2) Then
OwnersNames.ControlSource = "=FirstName1] & " " & [LastName1]"
Else
OwnersNames.ControlSource = "=[FirstName1] & " " & [LastName1] & " and " & [FirstName2] & " " & [LastName2]"
End If
End Sub
If I'm reading this correctly, then try this which uses more quote marks to concatenate the statement:
Private Sub Report_Load()
If IsNull(FirstName2) Then
OwnersNames.ControlSource = "=[FirstName1]" & " " & "[LastName1]"
Else
OwnersNames.ControlSource = "=[FirstName1]" & " " & "[LastName1]" & " and " & "[FirstName2]" & " " & "[LastName2]"
End If
End Sub
If you are trying to concatenate the fields (e.g. 'add' them together). You need something like:
Private Sub Report_Load()
If IsNull(FirstName2) Then
OwnersNames.ControlSource = "=[FirstName1] & ' ' & [LastName1]"
Else
OwnersNames.ControlSource = "=[FirstName1] & ' ' & [LastName1] & ' ' & [FirstName2] & ' ' & [LastName2]"
End If
End Sub
Keep in mind you can concatenate text fields (e.g. text boxes) together.
I'm uncertain if combining the control sources of fields works the same way. To be sure, one option is to rename each textbox to something different from its control source.
Here's the code now, which when loaded produces 'John Smith And' even though the Firstname2 field is null.
Private Sub Report_Load()
If Me.FirstName2 = vbNullString Then
OwnersNames.ControlSource = "=[FirstName1] & ' ' & [LastName1]"
Else
OwnersNames.ControlSource = "=[FirstName1] & ' ' & [LastName1] & ' and ' & [FirstName2] & ' ' & [LastName2]"
End If
End Sub
Are you really meaning to set the control source or just the value of the field?
I think this might be what you want to accomplish????
Private Sub Report_Load()
If Me.FirstName2 = "" Then
me.OwnersNames = [FirstName1] & " " & [LastName1]
Else
me.OwnersNames = [FirstName1] & " " & [LastName1] & _
" and " & [FirstName2] & " " & [LastName2]
End If
End Sub

Form with multi-criteria searches - uses strings and filters

I have a search form with blank fields tied to a table, four criteria search boxes, and a button to take the input from the search boxes, search the table, and populate the results on the form's blank fields.
As of now, it works as long as all four criteria boxes aren't null.
I used filters to achieve this, and here's the code that works as long as all four boxes are not empty. (My criteria boxes are as follows: a textbox called "Keyword" and three combo boxes called HRCombo, BuildingCombo, and RoomCombo, and the fields they're tied to are as follows: "Item Description" "HR Holder" "Building" "Room") My first line "Me.Filter = ..." was broken up to make it easier to view.
Me.Filter = "[Item Description] Like " & Chr(34) & Me.Keyword & "*" & Chr(34) & "
AND [HR Holder] = '" & Me.HRCombo & "'" & " AND [Building] = '" & Me.BuildingCombo
& "'" & " AND [Room] = '" & Me.RoomCombo & "'"
Me.FilterOn = True
Me.Requery
I need it to be able to do the search no matter which combination of criteria boxes have input. Someone recommended using if statements to do the following:
Create four strings, one for each criteria box. Use 4 if statements to check if the box is null - if it is null, assign an asterisk to its string, and if its not null, assign the value I used for the above Me.Filter statement to each box's string. Then, use Me.Filter and concatenate the four strings at the end.
Here's the code I used for this, and, with my limited knowledge, I can't get it to work.
Dim StrA as String, StrB as String, StrC as String, StrD as String
If Me.Keyword is null then
StrA = "*"
else
StrA = [Item Description] Like " & Chr(34) & Me.Keyword & "*" & Chr(34)
End If
If Me.HRCombo is null then
StrB = "*"
else
StrB = [HR Holder] = '" & Me.HRCombo & "'"
End If
If Me.BuildingCombo is null then
StrC = "*"
else
StrC = [Building] = '" & Me.BuildingCombo & "'"
End If
If Me.RoomCombo is null then
StrD = "*"
else
StrD = [Room] = '" & Me.RoomCombo & "'"
End If
Me.Filter = "StrA & " AND "StrB & " AND "StrC &" AND "StrD"
Me.FilterOn = True
Me.Requery
Like I said, I have a limited knowledge, so I'm sure there's probably missing quotes and commas, or too many of them. Any ideas?
You're missing some important quotes and your logic to check for null is correct for SQL but not correct for VBA. I'm posting here what I believe is a cleaner way of doing this. Just be aware that you're not escaping single quotes that might be entered in your controls and neither am I in this code (except in the first one, just so you can see how to do it using the Replace function). That's a pretty important thing to do any time a single quote could possibly land up in one of the search/filtering controls.
Dim strWhere as String
If Nz(Me.Keyword, "") <> "" Then
strWhere = strWhere & "[Item Description] Like '*" & Replace(Me.Keyword, "'", "''") & "*' AND "
End If
If Nz(Me.HRCombo, "") <> "" Then
strWhere = strWhere & "[HR Holder] = '" & Me.HRCombo & "' AND "
End If
If Nz(Me.BuildingCombo, "") <> "" Then
strWhere = strWhere & "[Building] = '" & Me.BuildingCombo & "' AND "
End If
If Nz(Me.RoomCombo, "") <> "" Then
strWhere = strWhere & "[Room] = '" & Me.RoomCombo & "' AND "
End If
If strWhere <> "" Then
strWhere = Left(strWhere, Len(strWhere)-5) 'Remove the extra AND
Me.Filter = strWhere
Me.FilterOn = True
Else
Me.Filter = ""
Me.FilterOn = False
End If