Project #2: Alerting the User of Errors

Topprs
0

 In this project, let's create a macro that alerts the user if there are any errors while processing the data. We'll use Excel's built-in error handling mechanism to detect errors and provide informative messages to the user.

Here's how we can do it:

Prompt User for Input: Similar to the previous project, we'll prompt the user to enter data, such as prices and quantities of items.

Error Handling: We'll implement error handling to check for any issues that might arise during data processing.

Alert User of Errors: If an error occurs, we'll display a meaningful message to the user explaining the issue.

Here's the VBA code for this project:

Sub CalculateTotalCostWithErrorHandling() 
Dim price As Variant 
Dim quantity As Variant 
Dim totalCost As Double 
' Prompt user for input: price and quantity 
price = InputBox("Enter the price of the item:", "Item Price") 
quantity = InputBox("Enter the quantity of the item:", "Item Quantity") 
' Check if user canceled input 
If price = "" Or quantity = "" Then 
MsgBox "Operation canceled by the user." 
Exit Sub 
End If 
' Error handling: Check if input is numeric On Error Resume Next 
price = CDbl(price) 
quantity = CInt(quantity) 
If Err.Number <> 0 Then 
MsgBox "Invalid input. Please enter numeric values for price and quantity." 
Exit Sub 
End If On Error GoTo 0 
' Turn off error handling 
' Check if quantity is negative 
If quantity <= 0 Then 
MsgBox "Quantity must be a positive integer." 
Exit Sub 
End If 
' Calculate total cost 
totalCost = price * quantity 
' Display result 
MsgBox "Total cost: $" & Format(totalCost, "0.00") 
End Sub

To use this macro:

Press Alt + F11 to open the Visual Basic for Applications (VBA) editor.

Insert a new module from Insert > Module.

Copy and paste the code into the module window.

Close the VBA editor.

You can now run the macro by pressing Alt + F8, selecting CalculateTotalCostWithErrorHandling, and clicking Run.

This macro prompts the user to enter the price and quantity of an item. It then performs error handling to check for issues such as non-numeric input or negative quantities. If any errors are detected, it displays a message to the user explaining the issue. If no errors occur, it calculates the total cost and displays it to the user.

Post a Comment

0Comments

Either way the teacher or student will get the solution to the problem within 24 hours.

Post a Comment (0)
close