Pop Up Message when the Stock Levels reach the Critical Level - vba

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.

Related

Checking a box based on criteria in VBA Access

I'm trying to figure out the best way to have my checkbox "checked" when my user clicks Yes when validating approvals. The checkbox column lives in the retailEntry table but I added it to my approval query so they should be linked.
The problem is that all "pack_numbers" are checked even the ones not present on the approval query. I want only the packs that appear on the approvalqry to be checked. It appears I cannot "Check" the "Creative Approval" from the approvalqry and if I use the retailentry recordset it just checks everything.
Any advice or push in the right direction would be greatly appreciated!
Code:
Set rap = CurrentDb.OpenRecordset("Approvalqry")
Set rs = CurrentDb.OpenRecordset("RetailEntry")
On Error Resume Next
If Not (rap.EOF And rap.BOF) Then
rap.MoveFirst
Do Until rs.EOF = True
If rap.RecordCount > 0 Then
nConfirmation = MsgBox("PackNumber " & rap.Fields("Pack_Number") & " Offer " & rap.Fields("Catid") & " is currently in the Proofing Stage, and will require Approval from CMS - Creative, and Divisional Merch Manager. Confirm Approvals have been received?", vbInformation + vbYesNo, "Approval Required!")
If nConfirmation = vbYes Then
'Update approved checkbox
If rap.Fields("Pack_Number").Value Then
rap.Edit
rap![Creative Approval] = True
rap.Update
Else
End If
Else
MsgBox "Please obtain Late Retail Change Approval for this product within Offer " & rap.Fields("Catid") & ", then resubmit your request."
ClearTables
End
End If
End If
rap.MoveNext
rst.MoveNext
rs.MoveNext
Me.Requery
Loop
End If
On Error GoTo 0
Err.Clear

How to refill combobox with similar records based on what user types

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

SQL - Save record with listbox and textbox change

I have a list box - The user clicks one of the results in the list box that's populated from a table.
When they click one of the items in a list box the text boxes populate the results that are in the table
On the textbox I have on change code of:
DoCmd.RunSQL "UPDATE tbl_ComplaintsCoded SET [TicketNumber] = '" & Text3 & "' WHERE ID = " & List1.Column(0)
Text3 shows the Ticket number
Text5 shows the department
Its the department that the user is trying to change before getting an error of:
data type mismatch in criteria expression
Thanks for the help
Just for fun, I rewrote what you put together in something a little more elegant with some basic error handling and a little more streamlined.
Option Compare Database
'Added the option explicit to verify your variables
Option Explicit
Private Sub Button_Click()
'ERROR HANDLING
On Error GoTo Button_Click_Err_Handler
Dim rs As DAO.Recordset
'Is your TicketNumber column a Text data type? Me.List1.Column(0) should return a variant value, so assuming
'your TicketNumber column is of a number type as the name implies, I think you could just use:
'Set rs = CurrentDb.OpenRecordset("SELECT * FROM tbl_name WHERE TicketNumber = " & Me.list1.Column(0))
Set rs = CurrentDb.OpenRecordset("SELECT * FROM tbl_name WHERE TicketNumber = '" & Me.list1.Column(0) & "'")
'You should always check for BOF and EOF if you're checking if there is no record.
If rs.BOF And rs.EOF Then
MsgBox "You have not selected a record, nothing to save!", vbInformation
'Exiting here, instead of wrapping the entire sub in the if... ...end if statement. You could also just use "Exit Sub", but I added
'the exit and error handling to make it a little more graceful.
GoTo Button_Click_Exit
End If
'I wrapped the rs edits in a with statement and used the direct column name operator ! instead of the collection searching rs() feature.
'For illustration, I wrapped a few of the references in the Nz() function. If none of the fields are ever null, bravo to you for excellent
'database design and database users discipline, but I almost always have a couple columns where nulls are allowed.
With rs
.Edit
'Top Categories
!Business = Me.Text5
!Status = Me.Text8
!MailDate = Me.Text10
'Complaint Detail Section
!Type = Me.Text19
!Sub = Me.Text21
!c = Me.Text23
'Complaint Coding Section
!touch2 = Me.Combo29
!touch1 = Me.Combo33
!Cause2 = Me.Combo31
!cause1 = Me.Combo35
'CS Account Details Section
!Account = Me.Text39
!Feed = Me.Combo41
'Logged Audit User
!LoggedUser = Me.Text43
!DateTimeLogged = Me.Text49
.Update
End With
'EXIT PROCEDURE
Button_Click_Exit:
On Error Resume Next
Exit Sub
'ERROR HANDLING
Button_Click_Err_Handler:
MsgBox Err.Number & Err.Description, vbOKOnly + vbCritical, "Error"
Resume Button_Click_Exit
End Sub
I solved this by doing this instead:
Set db = CurrentDb
Set rec = db.OpenRecordset("Select * from tbl_name WHERE TicketNumber = '" & Me.List1.Column(0) & "'")
If rec.EOF Then
MsgBox "You have not selected a record, nothing to save!", vbInformation
Else
rec.Edit
'Top Categories
rec("Business") = Me.Text5
rec("Status") = Me.Text8
rec("MailDate") = Me.Text10
'Complaint Detail Section
rec("Type") = Me.Text19
rec("Sub") = Me.Text21
rec("C") = Me.Text23
'Complaint Coding Section
rec("touch2") = Me.Combo29
rec("touch1") = Me.Combo33
rec("Cause2") = Me.Combo31
rec("cause1") = Me.Combo35
'CS Account Details Section
rec("Account") = Me.Text39
rec("Feed") = Me.Combo41
'Logged Audit User
rec("LoggedUser") = Me.Text43
rec("DateTimeLogged") = Me.Text49
rec.Update

VBA - Check multiple comboboxes

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.

#Name? on form after requery in Access 2010

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