Continue Automate SUM Function

Topprs
0

 Certainly! Let's continue to enhance the automation of the SUM() function by allowing users to input the range dynamically using an InputBox. We'll also handle cases where the user cancels the input or enters an invalid range.

Here's the updated code:

Sub AutomateSUMFunction() 
Dim sumRange As Range 
Dim total As Double 
' Prompt the user to input the range 
On Error Resume Next 
Set sumRange = Application.InputBox("Select the range to sum:", Type:=8) 
On Error GoTo 0 
' Check if user canceled or entered an invalid range 
If sumRange Is Nothing Then 
MsgBox "Operation canceled or invalid range entered." Exit Sub End If 
' Check if selected range is valid for calculation 
If Not IsNumeric(Application.WorksheetFunction.Sum(sumRange)) Then 
MsgBox "Selected range contains non-numeric values." 
Exit Sub 
End If 
' Calculate the sum 
total = Application.WorksheetFunction.Sum(sumRange) 
' Display the result 
MsgBox "The sum of the selected range is: " & total 
End Sub

In this updated version:

We use Application.InputBox to prompt the user to select the range dynamically. The Type:=8 parameter specifies that the input should be a range.

We handle cases where the user cancels the input or enters an invalid range by checking if sumRange is Nothing.

We verify if the selected range contains only numeric values using IsNumeric.

Finally, we calculate the sum using Application.WorksheetFunction.Sum() and display the result in a message box.

Now, users can dynamically select the range they want to sum, and the macro will handle various scenarios gracefully, providing informative messages in case of errors or invalid inputs.

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