I have the below code where I'm trying to check comboboxes to make sure they are not null
I have a core combobox - cmbHierarchy - with Store, Retailer, Territory, District and secondary comboboxes to select stores, retailers, territories, districts (one for each)
I want the VBA to check cmbHierarchy to make sure it's populated, then depending on what it is populated with, make sure it's corresponding combobox has a value selected.
The current code is checking to make sure all 5 are populated. Where what I need is if cmbHierarchy = store then check cmbStore, if cmbHierarchy = retailer then check retailer, and so on.
Private Sub btnQryTermCount_Click()
Dim strQueryName As String
If Me.cmbHierarchy.Value = Store Or IsNull(Me.cmbStore.Value) Then
MsgBox "Please choose a Store"
Me.cmbStore.SetFocus
ElseIf Me.cmbHierarchy.Value = Retailer Or IsNull(Me.cmbRetailer.Value) Then
MsgBox "Please choose a Retailer"
Me.cmbRetailer.SetFocus
Else: strQueryName = "TERM_Count_" & Me.cmbHierarchy
MsgBox "Query Ready: " & strQueryName
DoCmd.OpenQuery strQueryName
End If
End Sub
Any help would be greatly appreciated.
Thanks!
Since your controls are named conveniently, you can do something like this:
If Nz(Me.cmbHierarchy.Value, "") <> "" Then
If Nz(Me.Controls("cmb" & Me.cmbHierarchy.Value).Value) = "" Then
MsgBox "Please choose a " & Me.cmbHierarchy.Value & "."
Else
strQueryName = "TERM_Count_" & Me.cmbHierarchy.Value
MsgBox "Query Ready: " & strQueryName
DoCmd.OpenQuery strQueryName
End If
Else
'cmbHierarchy validation failed logic here.
End if
IsNull instead of Nz maybe fine, but I am always in the habit of casting the value to be safe.
Related
I'm currently building a form where a user can look up a tool based on the description or part number.
I want user to be able to type any letters into the combobox that I have tied to a query listing all my tools and the combobox will repopulate itself with the tools most similar to what is present in their combobox. For example, if they start typing wre, then tools that have similar characters will start appearing in the combobox such as wrench, torque wrench, power wrench, etc.
I've tried looking around for other people's solutions to this but either I didn't fully comprehend the existing solution (I'm fairly new to Access) or it wasn't what I was looking for. I've seen that people suggested using a listbox instead but I really don't want to go down that route.
I was thinking about using what the user types in the combobox and my VBA code will pick up the "change event" and requery the combobox on the fly by using their input as the like criteria for the new query.
Is this a possible route? Will it be slower? Is there a better route?
I'm hoping someone can show some examples on how to achieve what I'm looking for.
The search as you type feature is very useful! With a textbox and a listbox, you can setup a dynamic search tool that will filter a list for approximate matches as you type. The textbox has four events associated with it, as seen here.
The code behind the form looks like this. Pay attention to the part in bold. This is where we create a string of SQL commands, and utilize the SQL Like operator, to get dynamic matches as we type. Pay attention to the text in bold below.
Option Compare Database
Option Explicit On
Private blnSpace As Boolean 'INCLUDE THIS LINE ON YOUR FORM
Private Sub btnClearFilter_Click()
'CODE FOR THE RED "X" BUTTON TO CLEAR THE FILTER AND SHOW ALL
On Error Resume Next
Me.txtSearch.Value = ""
txtSearch_Change()
End Sub
Private Sub txtSearch_Change()
'CODE THAT HANDLES WHAT HAPPENS WHEN THE USER TYPES IN THE SEARCH BOX
Dim strFullList As String
Dim strFilteredList As String
If blnSpace = False Then
Me.Refresh 'refresh to make sure the text box changes are actually available to use
'specify the default/full rowsource for the control
strFullList = "SELECT RecordID, First, Last FROM tblNames ORDER BY First;"
'specify the way you want the rowsource to be filtered based on the user's entry
strFilteredList = "SELECT RecordID, First, Last FROM tblNames WHERE [First] LIKE ""*" & Me.txtSearch.Value &
"*"" OR [Last] LIKE ""*" & Me.txtSearch.Value & "*"" ORDER BY [First]"
'run the search
fLiveSearch Me.txtSearch, Me.lstItems, strFullList, strFilteredList, Me.txtCount
End If
End Sub
Private Sub txtSearch_KeyPress(KeyAscii As Integer)
'NECESSARY TO IDENTIFY IF THE USER IS HITTING THE SPACEBAR
'IN WHICH CASE WE WANT TO IGNORE THE INPUT
On Error GoTo err_handle
If KeyAscii = 32 Then
blnSpace = True
Else
blnSpace = False
End If
Exit Sub
err_handle:
Select Case Err.Number
Case Else
MsgBox "An unexpected error has occurred: " & vbCrLf & Err.Description &
vbCrLf & "Error " & Err.Number & "(" & Erl() & ")"
End Select
End Sub
Private Sub txtSearch_GotFocus()
' USED TO REMOVE THE PROMPT IF THE CONTROL GETS FOCUS
On Error Resume Next
If Me.txtSearch.Value = "(type to search)" Then
Me.txtSearch.Value = ""
End If
End Sub
Private Sub txtSearch_LostFocus()
' USED TO ADD THE PROMPT BACK IN IF THE CONTROL LOSES FOCUS
On Error Resume Next
If Me.txtSearch.Value = "" Then
Me.txtSearch.Value = "(type to search)"
End If
End Sub
Finally, in a regular module, you will need this script.
Option Compare Database
Option Explicit On
'************* Code Start **************
' This code was originally written by OpenGate Software
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
' OpenGate Software http://www.opengatesw.net
Function fLiveSearch(ctlSearchBox As TextBox, ctlFilter As Control,
strFullSQL As String, strFilteredSQL As String, Optional ctlCountLabel As Control)
Const iSensitivity = 1 'Set to the number of characters the user must enter before the search starts
Const blnEmptyOnNoMatch = True 'Set to true if you want nothing to appear if nothing matches their search
On Error GoTo err_handle
'restore the cursor to where they left off
ctlSearchBox.SetFocus
ctlSearchBox.SelStart = Len(ctlSearchBox.Value) + 1
If ctlSearchBox.Value <> "" Then
'Only fire if they've input more than two characters (otherwise it's wasteful)
If Len(ctlSearchBox.Value) > iSensitivity Then
ctlFilter.RowSource = strFilteredSQL
If ctlFilter.ListCount > 0 Then
ctlSearchBox.SetFocus
ctlSearchBox.SelStart = Len(ctlSearchBox.Value) + 1
Else
If blnEmptyOnNoMatch = True Then
ctlFilter.RowSource = ""
Else
ctlFilter.RowSource = strFullSQL
End If
End If
Else
ctlFilter.RowSource = strFullSQL
End If
Else
ctlFilter.RowSource = strFullSQL
End If
'if there is a count label, then update it
If IsMissing(ctlCountLabel) = False Then
ctlCountLabel.Caption = "Displaying " & Format(ctlFilter.ListCount - 1, "#,##0") & " records"
End If
Exit Function
err_handle:
Select Case Err.Number
Case 91 'no ctlCountLabel
'exit
Case 94 'null string
'exit
Case Else
MsgBox "An unexpected error has occurred: " & vbCrLf & Err.Description &
vbCrLf & "Error " & Err.Number & vbCrLf & "Line: " & Erl()
End Select
End Function
The code comes from this link:
http://www.opengatesw.net/ms-access-tutorials/Access-Articles/Search-As-You-Type-Access.html
The Basic Function of this is that when you Log in to the system and when on load of the Main Menu it should show a message if certain Products have reached the critical level and when you press yes it should redirect to the form where it shows a detailed view.
In this Case the Quantity in hand is "QTY" and Critical Level is "ROQ" (Field names in the tblProduct)
Dim Alert As Integer
Dim rsAlert As New Adodb.Recordset
rsAlert.Open "select * from tblproduct , CurrentProject.Connection"
Alert = DCount("[qty]", "[tblProduct]", " [ROQ] <= Qty and =0")
If Alert = 0 Then
Exit Sub
Else
If MsgBox("This/These " & Alert & " product/products have reached their critical levels" & _
vbCrLf & vbCrLf & "Would you like to see these now?", _
vbYesNo, "Alert...") = vbYes Then
DoCmd.Minimize
DoCmd.OpenForm "frmAlerts", acNormal
Else
Exit Sub
End If
End If
End Sub
The error I get is that when load my menu menu it doesn't show the number of products which are under the critical level ! If anyone can help it would be a Great Help!
This has been done in Microsoft Access.
Further to my comment this is a not going to work. Create a list box and populate it with the stock shortages, something like this;
Dim rsAlert As Recordset
Dim sSql As String
sSql = "SELECT ProductID, Description, OtherFields, GoHere FROM tblproduct WHERE ROQ >= QTY AND ROQ > 0"
Set rsAlert = CurrentDb.OpenRecordset(sSql, dbOpenSnapshot)
If Not rsAlert.EOF Then 'There are records (shortages) so unhide and poulate the list box (called lstShortageListBox)
Me.lstShortageListBox.Visible = True
Me.lstShortageListBox.RowSource = sSql
Else
Me.lstShortageListBox.Visible = False
End If
' Tidy Up
rsAlert.Close
Set rsAlert = Nothing
Obviously make sure that the recordsets criteria are correct - I've made some guesses about that bit.
I have a form with multiple list boxes and all work fine save 1! This is the only list box whose source is number data-type. I know this shouldn't matter, but what I'm seeing is that for this list box only the variant returned is always 1, and I cannot understand why the others (data-type text) work properly and this one doesn't. All of my Google searches and MSN searches and here on StackOverflow have not helped my specific issue though there's a LOT out there about ListBoxes. Please help!
Edit: Sorry #Mat's Mug...I was hoping that wouldn't be necessary as it's lengthy with all the checking going on, but here's the gist.
For Each ctl In Form.Controls
With ctl
Select Case .ControlType
Case acListBox
If .Visible = True Then
.SetFocus
ItemCount = .ItemsSelected.Count
If .ItemsSelected.Count > 0 Then
For Each varItm In .ItemsSelected
If .Name = "lstRating" Then
sWhereClause = sWhereClause & "ThisRating=" & .ItemData(varItem) & " Or ThatRating = " & .ItemData(varItem)
Else
sWhereClause = sWhereClause & Mid(.Name, 4, Len(.Name)) & " = """ & .ItemData(varItm) & """"
End If
Next varItm
End If
End If
End Select
End With
Next ctl
Note: When .Name = "lstRating" is True is the line where varItem returned is 1 regardless of what is selected. The list box is populated with values from 1 to 5 in 0.5 increments.
Well, I can't believe I was overlooking it for hours...I was using varItem in the offending line when it's defined at varItm, no "e"! TOTALLY an oversight on my part. Thanks all for looking into this!
My task is create a query that is filtered by the results of a listbox with multiselect. I have a table, named contacts, which has a field named 'Sources'. This is the field that is displayed in my listview. I am sorting by the 'Sources' value
From here, I can multiselect the options, and hit a submit button. When I do so, I get a query but it seems to simply display all of the values.
Therefore, my question is, how can I create a query sorted by the Sources tab? I know that I need a onclick function, but I am very unfamiliar with VB. Any help would be appreciated!
You can modify the following to use your control names. You didn't mention where/how your query is created, but you can merge this code with yours...
Private Sub cmdBuildWhere_Click()
Dim varItem As Variant
Dim strWhere As String
If Me.lstHierarchy.ListIndex < 1 And Me.lstHierarchy.ItemsSelected.Count = 0 Then ' No items selected
MsgBox "You did not select any sources. ", vbOKOnly, "Select Sources"
Exit Sub
End If
strWhere = "WHERE "
For Each varItem In Me.lstHierarchy.ItemsSelected
strWhere = strWhere & "[Sources] = '" & Me.lstHierarchy.Column(0, varItem) & "' Or "
Next varItem
' remove final ' or ' and add Sort
strWhere = Trim(left(strWhere, Len(strWhere) - 4)) & " Order By Sources;"
Debug.Print strWhere
End Sub
I am using VBA and SQL to re-query my main form based on criteria entered in several controls on a pop up form. As far as I can tell the code is running correctly, the database is re-queried based on the criteria I enter, but 2 of my controls on my main form show as #Name? or blank after re-querying based on the criteria. Anyone know how I can fix this???
The code that runs the re-query is:
Public Sub SuperFilter()
On Error GoTo Err_AdvancedFilter_Click
Dim strSQL As String
Dim strCallNumber As String
Dim strAsgnTech As String
Dim strClientID As String
Dim strCallGroup As String
Dim strPriority As String
Dim strOpenStatus As String
If IsNull(Forms![frmTips&Tricks].txtCallNumber) = False Then
strCallNumber = " (((CallInfo.CallNumber) = forms![frmTips&Tricks].[txtCallNumber])) and "
Else
strCallNumber = ""
End If
If IsNull(Forms![frmTips&Tricks].cboAsgnTech) = False Then
strAsgnTech = " (((CallInfo.AsgnTech) = forms![frmTips&Tricks].[cboasgntech])) and "
Else
strAsgnTech = ""
End If
If IsNull(Forms![frmTips&Tricks].cboClientID) = False Then
strClientID = " (((CallInfo.ClientID) = forms![frmTips&Tricks].[cboClientID])) and "
Else
strClientID = ""
End If
If IsNull(Forms![frmTips&Tricks].cboCallGroup) = False Then
strCallGroup = " (((CallInfo.AsgnGroup) = forms![frmTips&Tricks].[cboCallGroup])) and "
Else
strCallGroup = ""
End If
If IsNull(Forms![frmTips&Tricks].cboPriority) = False Then
strPriority = " (((CallInfo.Severity) = forms![frmTips&Tricks].[cboPriority])) and "
Else
strPriority = ""
End If
If Forms![frmTips&Tricks].optOpenStatus.Value = 1 Then
strOpenStatus = " (((CallInfo.OpenStatus) = True))"
Else
strOpenStatus = " (((CallInfo.OpenStatus) is not null ))"
End If
strSQL = "SELECT CallInfo.CallNumber, CallInfo.ClientID,* " & _
"FROM dbo_HDTechs INNER JOIN ([User] INNER JOIN CallInfo ON User.ClientID = CallInfo.ClientID) ON dbo_HDTechs.TechName = CallInfo.AsgnTech " & _
"WHERE " & strCallNumber & strAsgnTech & strClientID & strCallGroup & strPriority & strOpenStatus & _
"ORDER BY CallInfo.RcvdDate;"
Form.RecordSource = strSQL
Me.cboCallNumber.RowSource = strSQL
Form.Requery
If Me.RecordsetClone.RecordCount = 0 Then
MsgBox "No Records Found: Try Diferent Criteria."
Form.RecordSource = "qryservicerequestentry"
Me.cboCallNumber.RowSource = "qryservicerequestentry"
Exit Sub
End If
Me.cmdSuperFilterOff.Visible = True
Exit Sub
Exit_cmdAdvancedFilter_Click:
Exit Sub
Err_AdvancedFilter_Click:
MsgBox Err.Description
Resume Exit_cmdAdvancedFilter_Click
End Sub
The first control in question is a combo box that displays the Client Name from the CallInfo form (Main Form).
Control Source: ClientID
And when expanded lists all available clients to select from the Users form (User ID is linked between the User form and CallInfo form).
Row Source: SELECT User.ClientID FROM [User];
After the re-query, this combobox will be blank, sometimes showing #Name? if you click on it.
The second control in question is a text box that shows the Client's phone number.
Control Source: PhoneNo
After the Re-query, this text box always displays #Name?
The third control in question is a text box that displays the clients office location.
Control Source: Location
What really baffles me is that THIS text box displays correctly after the re-query. I don't know why it would display the correct data when the Phone Number text box does not, seeing as they are so similar and work with similar data....
To Compare, the The form record source is normally based on:
SELECT CallInfo.CallNumber, CallInfo.ClientID, CallInfo.RcvdTech, CallInfo.RcvdDate, CallInfo.CloseDate, CallInfo.Classroom, CallInfo.Problem, CallInfo.CurrentStatus, CallInfo.Resolution, CallInfo.Severity, CallInfo.OpenStatus, CallInfo.AsgnTech, dbo_HDTechs.Email, CallInfo.FullName, CallInfo.AsgnGroup, User.Location, User.PhoneNo, CallInfo.OpenStatus
FROM dbo_HDTechs INNER JOIN ([User] INNER JOIN CallInfo ON User.ClientID = CallInfo.ClientID) ON dbo_HDTechs.TechName = CallInfo.AsgnTech
WHERE (((CallInfo.OpenStatus)=True))
ORDER BY CallInfo.RcvdDate;
Just going on what you wrote, I may take a slightly different approach (just personal preference).
I would change all of your 'IsNull' tests to also check for 'Empty'. i.e.
If IsNull(Forms![frmTips&Tricks].cboClientID) = False AND ...cliientID <> ""
Just today I had an issue relating to form references in a query WHERE clause, so I changed to:
strClientID = " (((CallInfo.ClientID) = '" & forms![frmTips&Tricks].[cboClientID] & "')) and"
Add a Debug.Print of your generated SQL, then look at it and try to run that SQL manually
Good Luck,
Wayne
Solved by designating the form in the control source like: CallInfo.ClientID
I still don't know why the Client Office displayed Correctly... Anybody have a hint? :)
TE