The cancel button doesn't work for this code [duplicate] - excel

I have the following piece of code:
dim selectRange as Range
Set selectRange = Application.InputBox("Select your range", "Hello", , , , , , 8)
When a user chooses Cancel the InputBox prompt, it returns error of Object not set.
I have tried to use a Variant variable type but I can't handle it. In case of cancelling, it returns False, meanwhile in case of selecting a range, it returns Range of InputBox.
How can I avoid this error?

This is a problem when selection a range with an inputbox. Excel returns an error before the range is returned, and it carries this error on when you press cancel.
You should therefore actively handle this error. If you don't want anything to happen when you press cancel, you can just use the code like this:
Sub SetRange()
Dim selectRange As Range
On Error Resume Next
Set selectRange = Application.InputBox("Select your range", "Hello", , , , , , 8)
Err.Clear
On Error GoTo 0
End Sub

While this question is a bit older I still want to show the proper way to do it without errors. You can do it either to it via function or with a sub.
Your main procedure is something like this:
Sub test()
Dim MyRange As Range
testSub Application.InputBox("dada", , , , , , , 8), MyRange 'doing via Sub
Set MyRange = testFunc(Application.InputBox("dada", , , , , , , 8)) ' doing via function
If MyRange Is Nothing Then
Debug.Print "The InputBox has been canceled."
Else
Debug.Print "The range " & MyRange.Address & " was selected."
End If
End Sub
the Sub-way (funny) would be:
Sub testSub(ByVal a As Variant, ByRef b As Range)
If TypeOf a Is Range Then Set b = a
End Sub
And the function would look like:
Function testFunc(ByVal a As Variant) As Range
If TypeOf a Is Range Then Set testFunc = a
End Function
Now simply use the way you like and delete the unused line.
If calling a sub or a function you do not need to Set the parameter. That said, it doesn't matter if the InputBox returns an object or not. All you need to do, is to check if the parameter is the object you want or not and then act accordingly to it.
EDIT
Another smart way is using the same behavior with a collection like this:
Sub test()
Dim MyRange As Range
Dim MyCol As New Collection
MyCol.Add Application.InputBox("dada", , , , , , , 8)
If TypeOf MyCol(1) Is Range Then Set MyRange = MyCol(1)
Set MyCol = New Collection
If MyRange Is Nothing Then
Debug.Print "The inputbox has been canceled"
Else
Debug.Print "the range " & MyRange.Address & " was selected"
End If
End Sub
If you still have any questions, just ask ;)

I'm late to the party here but this was the only place I could find that explained why I was having trouble just checking my variable for nothing. As explained in the accepted answer, the vbCancel on a range object isn't handled the same way as a string object. The error must be caught with an error handler.
I hate error handlers. So I segregated it to its own function
Private Function GetUserInputRange() As Range
'This is segregated because of how excel handles cancelling a range input
Dim userAnswer As Range
On Error GoTo inputerror
Set userAnswer = Application.InputBox("Please select a single column to parse", "Column Parser", Type:=8)
Set GetUserInputRange = userAnswer
Exit Function
inputerror:
Set GetUserInputRange = Nothing
End Function
Now in my main sub I can
dim someRange as range
set someRange = GetUserInputRange
if someRange is Nothing Then Exit Sub
Anyhow this is not the same as the accepted answer because it allows the user to only handle this error with a specific error handler and not need to resume next or have the rest of the procedure handled the same way. In case anyone ends up here like I did.

I have found that checking for the "Object required" error that you mentioned is one way of handling a cancel.
On Error Resume Next
dim selectRange as Range
' InputBox will prevent invalid ranges from being submitted when set to Type:=8.
Set selectRange = Application.InputBox("Select your range", "Hello", , , , , , 8)
' Check for cancel: "Object required".
If Err.Number = 424 Then
' Cancel.
Exit Sub
End If
On Error GoTo 0

I went with a cleaner solution:
Dim InputValue As Range
On Error Resume Next
Set InputValue = Application.InputBox("Select Range","Obtain Range", Type:=8)
Err.Clear
If InputValue Is Nothing Then
GoTo ExitApp:
End If
This will clear the error message and catch the "nothing" value returned to InputValue. Usefully, this doesn't interrupt a submission of no information, which Excel just loops back to requesting input automatically, but the user may need to add additional error handling for bad data entry.
Down code, add:
ExitApp:
Exit Sub
For exiting, which can be usefully shared between multiple input cancel handlers.

If I use Dirks second answer inside a for loop and I want to exit my sub, it is not enough to execute an Exit Sub inside his IF statement
I found that if I use Exit Sub standalone inside a for loop, I will not exit my sub in all cases, however, in most cases only exit the for loop.
Here you have Dirks code
EDIT
Another smart way is using the same behavior with a collection like
this:
Sub test()
Dim MyRange As Range
Dim MyCol As New Collection
MyCol.Add Application.InputBox("dada", , , , , , , 8)
If TypeOf MyCol(1) Is Range Then Set MyRange = MyCol(1)
Set MyCol = New Collection
If MyRange Is Nothing Then
Debug.Print "The input box has been canceled"
Else
Debug.Print "the range " & MyRange.Address & " was selected"
End If
End Sub
If you still have any questions, just ask ;)
Here is what I made to work as a example:
Sub test()
Dim i as Integer
Dim boolExit as Boolean
Dim MyRange As Range
Dim MyCol As New Collection
boolExit = False
For i = 1 To 5 Then
MyCol.Add Application.InputBox("dada", , , , , , , 8)
If TypeOf MyCol(1) Is Range Then Set MyRange = MyCol(1)
Set MyCol = New Collection
If MyRange Is Nothing Then
Debug.Print "The inputbox has been canceled"
boolExit = True
Exit Sub
Else
Debug.Print "the range " & MyRange.Address & " was selected"
End If
Next i
If boolExit = True Then Exit Sub 'Checks if Sub should be exited
Debug.Print "Program completed"
End Sub
If you press cancel at anytime in the five runs, the Sub is shutdown with the above code and you will never see Program completed printed.
However if you remove boolExit from the above, the code after the For loop is still being run if you press cancel in any of the 1+ runs and you will see Program completed even when that is not true.

Related

How to handle blank/Invalid data for RefEdit control in VBA userform

I am using a Excel VBA userform to change the font case as below picture. When RefEdit control have correct Range, then it is working fine. But if I click "Apply" button keeping RefEdit blank/ only Space/ any word(invalid Range), Userform disappear without showing any error notification.
For Uppercase code:-
Sub UpperCaseFont()
For Each x In Range(CaseRefEdit.Value)
If Not IsEmpty(x.Value) Then
x.Value = UCase(x.Value)
End If
Next
MsgBox "Done"
End Sub
LowerCase code:-
Sub LowerCaseFont()
For Each x In Range(CaseRefEdit.Value)
If Not IsEmpty(x.Value) Then
x.Value = LCase(x.Value)
End If
Next
MsgBox "Done"
End Sub
Propercase code:-
Sub ProperCaseFont()
For Each x In Range(CaseRefEdit.Value)
If Not IsEmpty(x.Value) Then
x.Value = WorksheetFunction.Proper(x.Value)
End If
Next
End Sub
CommandButton code:-
Private Sub CaseApplyCommandButton_Click()
If UpperCase = True Then Call UpperCaseFont
If LowerCase = True Then Call LowerCaseFont
If ProperCase = True Then Call ProperCaseFont
For that reason, I have tried to modified as below, But still i am facing the problem that if RefEdit is blank and I click on "Apply" button then userform disappear and also found that other all userform start unknown problem to initialize.
Private Sub CaseApplyCommandButton_Click()
'Font Case
Dim Rng As Range
On Error Resume Next
Set Rng = Range(Me.CaseRefEdit.Value)
MsgBox Rng
On Error GoTo 0
If Rng Is Nothing Then
MsgBox "Select the Cells to change the case"
Else
If UpperCase = True Then Call UpperCaseFont
If LowerCase = True Then Call LowerCaseFont
If ProperCase = True Then Call ProperCaseFont
End If
End Sub
I have found that problem is started when I add below code:-
Private Sub CaseRefEdit_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Range(CaseRefEdit.Value).Select
End Sub
As per my understanding when RefEdit is not giving any range for input any number or word or keeping blank, then userform disappear. Any solution for this?
On the second question.
The [if IsError (range ("Hello") then ...] expression first evaluates the range ("Hello"), and if it is invalid, an error occurs before calling the function. Therefore, it is better to pass the address of the range to the IsError function, and calculate the range inside the function and determine its correctness.
Function IsError(addr As String) As Boolean
Dim rng As Range
On Error Resume Next
Set rng = Range(addr)
IsError = rng Is Nothing
End Function
Sub test1()
If IsError("%$%W34") Then
Debug.Print "Range is invalid"
Else
Debug.Print "Range is correct"
End If
End Sub
my problem is solved as below. Thanks #Алексей Р.
Private Sub CaseRefEdit_Exit(ByVal Cancel As MSForms.ReturnBoolean)
On error resume next
Range(CaseRefEdit.Value).Select
End Sub
Anyone know, how to check Range("etc")/ Range(123) is valid or not? Like-
If IsError(range("etc")) then
...
else
....
end if
You may use On Error statement, for example:
Function testRNG(addr As String) As Range ' returns correct Range object or Nothing otherwise
' initially testRNG = Nothing
On Error Resume Next
Set testRNG = Range(addr) ' if the address is correct, testRNG returns Range, otherwise an error occurs, the expression is not evaluated and testRNG remains Nothing
End Function
Sub foo()
Dim addr As String
addr = "W12"
Set Rng = testRNG(addr)
If Rng Is Nothing Then
Debug.Print "Address " & addr & " is wrong"
Else
Debug.Print "Range " & Rng.Address & " is correct"
End If
End Sub

Delete multiple selected Rows through radio button

the code I have prompt a popup requesting which row to delete, unfortunately when I press escape or cancel, whichever cell is active on the worksheet ends up getting deleted.
What I am looking for is a function where if I press escape on the keyboard or 'x' on the popup window it does not delete the row
Here is what I have so far:
Sub DeleteRow()
Dim rng As Range
Dim iRowCount As Integer
Dim iForCount As Integer
On Error Resume Next
Set selectedRng = Application.Selection
Set selectedRng = Application.InputBox("Range", , selectedRng.Address, Type:=8)
iRowCount = selectedRng.Rows.Count
For iForCount = iRowCount To 1 Step -1
If Application.WorksheetFunction.CountA(selectedRng.Rows(iForCount)) = 0 Then
selectedRng.Rows(iForCount).EntireRow.Delete
selectedRnd.Rows(iForCount).Delete
End If
Next
Application.ScreenUpdating = True
End Sub
The InputBox function returns a string, so using SET to assign the result to your selectedRng variable (which has not been declared, so will be considered a variant) will simply be skipped when the user cancels the input box. Therefore the variable will continue to hold the Application.Selection, which you assigned to it in the preceding line.
The input box returns "False" if the user click cancel or "X" or hits Escape.
I would try declaring a string variable to capture the result of the input, as in
dim strResult as string
strResult = Application.InputBox("Range", , selectedRng.Address)
if strResult <> "False" then
set selectedRng = Range(strResult)
'delete the rows now...
end if
Thank you guys,
I decided to completely simplify the code and it works fine now
Sub DeleteRow()
Dim Rng As Range, Num As String
On Error Resume Next
Set Rng = Application.InputBox(prompt:="Please Select Start Row ", Title:="Delete Rows", Type:=8)
If Split(Rng.Address, "$")(2) < 1 Then
'MsgBox "Please choose a Number Greater than 1"
Exit Sub
End If
Num = Application.InputBox(prompt:="Please Insert Number of Rows", Title:="Delete Rows", Type:=1)
If Num = False Then Exit Sub
Rng.Resize(Num).EntireRow.Delete
End Sub

Inputbox stopped accepting mouse selection in for each loop in excel vba because screenupdating changed in another sub--why?.

Why would an input box stop accepting a selection by mouse after a call to a sub with screenupdating variable changes?
I have a large workbook in excel that calculates a budget from different components on different sheets. I'm using named ranges in all of my formulas, and as I build the workbook I often need to move things around on the sheet, and thus edit the references to my named ranges so I made a macro to run through my named ranges and let me click to update their references.
I've included three subs from my workbook code; sheet 1 just has some values in the named range cells, a formula ( = CNGFixedCost1 + CNGFixedCost2 + CNGFixedCost3), and an activex check box. When I run RangeNameManager() the inputbox stops accepting mouse selections, due to the screenupdating variable in the Worksheet_Calculate() sub, . I figured out how to resolve the problem while writing this up (remove the screenupdating changes), but I'm still curious as to why this happens.
Option Explicit
'Name Ranges in workbook
Public Sub Workbook_Open()
Worksheets("Sheet1").Range("D3").Name = "CNGFixedCost1"
Worksheets("Sheet1").Range("D4").Name = "CNGFixedCost2"
Worksheets("Sheet1").Range("D5").Name = "CNGFixedCost3"
End Sub
'Update named ranges
Sub RangeNameManager()
Dim nm As Name
Dim nms As String
Dim xTitleID As String
Dim InputRng As Range
Dim asnms As String
On Error Resume Next
asnms = CStr(ActiveSheet.Name)
For Each nm In ActiveWorkbook.Names
nms = CStr(nm.Name)
If nm.RefersTo Like "*" & asnms & "*" Then
Set InputRng = ActiveSheet.Range("A1")
Set InputRng = Application.InputBox("The current range for" & nms & " is " & CStr(nm.RefersTo) & ". Select the new range.", InputRng.Address, Type:=8)
nm.RefersTo = InputRng
End If
Next
On Error GoTo 0
End Sub
' Update check box automatically
Private Sub Worksheet_Calculate()
Application.ScreenUpdating = False '***Removed to resolve problem.***
Dim errwksht As String
errwksht = ActiveSheet.Name
On Error GoTo ErrorHandler
If Worksheets("Sheet1").Range("CNGFixedCost1").Value > 0 Then
Worksheets("Sheet1").CheckBox1.Value = False
Else
Worksheets("Sheet1").CheckBox1.Value = True
End If
ErrorHandler:
Exit Sub
Application.ScreenUpdating = True '***Removed to resolve problem.***
End Sub
ScreenUpdating is a property of the Application object. If you turn it to false, then the application cuts off connection with the user (it won't take input, and it won't update the display).
It's very useful if you want to make something run faster, however it shouldn't be used during times when you need user interaction.
You're exiting the sub before turning screen updating back on, leaving the application in an unstable state.
' Update check box automatically
Private Sub Worksheet_Calculate()
Application.ScreenUpdating = False '***Removed to resolve problem.***
'...
ErrorHandler:
Exit Sub 'exits here
Application.ScreenUpdating = True ' so this NEVER executes
End Sub
This is easily fixed by resuming at your error handler, which would be better named CleanExit:. Here's how I would write it.
Private Sub Worksheet_Calculate()
On Error GoTo ErrorHandler
Application.ScreenUpdating = False '***Removed to resolve problem.***
'...
CleanExit:
Application.ScreenUpdating = True
Exit Sub
ErrorHandler:
' Actually do some error handling
Resume CleanExit
End Sub

Handle cancellation of InputBox to select range

I have the following piece of code:
dim selectRange as Range
Set selectRange = Application.InputBox("Select your range", "Hello", , , , , , 8)
When a user chooses Cancel the InputBox prompt, it returns error of Object not set.
I have tried to use a Variant variable type but I can't handle it. In case of cancelling, it returns False, meanwhile in case of selecting a range, it returns Range of InputBox.
How can I avoid this error?
This is a problem when selection a range with an inputbox. Excel returns an error before the range is returned, and it carries this error on when you press cancel.
You should therefore actively handle this error. If you don't want anything to happen when you press cancel, you can just use the code like this:
Sub SetRange()
Dim selectRange As Range
On Error Resume Next
Set selectRange = Application.InputBox("Select your range", "Hello", , , , , , 8)
Err.Clear
On Error GoTo 0
End Sub
While this question is a bit older I still want to show the proper way to do it without errors. You can do it either to it via function or with a sub.
Your main procedure is something like this:
Sub test()
Dim MyRange As Range
testSub Application.InputBox("dada", , , , , , , 8), MyRange 'doing via Sub
Set MyRange = testFunc(Application.InputBox("dada", , , , , , , 8)) ' doing via function
If MyRange Is Nothing Then
Debug.Print "The InputBox has been canceled."
Else
Debug.Print "The range " & MyRange.Address & " was selected."
End If
End Sub
the Sub-way (funny) would be:
Sub testSub(ByVal a As Variant, ByRef b As Range)
If TypeOf a Is Range Then Set b = a
End Sub
And the function would look like:
Function testFunc(ByVal a As Variant) As Range
If TypeOf a Is Range Then Set testFunc = a
End Function
Now simply use the way you like and delete the unused line.
If calling a sub or a function you do not need to Set the parameter. That said, it doesn't matter if the InputBox returns an object or not. All you need to do, is to check if the parameter is the object you want or not and then act accordingly to it.
EDIT
Another smart way is using the same behavior with a collection like this:
Sub test()
Dim MyRange As Range
Dim MyCol As New Collection
MyCol.Add Application.InputBox("dada", , , , , , , 8)
If TypeOf MyCol(1) Is Range Then Set MyRange = MyCol(1)
Set MyCol = New Collection
If MyRange Is Nothing Then
Debug.Print "The inputbox has been canceled"
Else
Debug.Print "the range " & MyRange.Address & " was selected"
End If
End Sub
If you still have any questions, just ask ;)
I'm late to the party here but this was the only place I could find that explained why I was having trouble just checking my variable for nothing. As explained in the accepted answer, the vbCancel on a range object isn't handled the same way as a string object. The error must be caught with an error handler.
I hate error handlers. So I segregated it to its own function
Private Function GetUserInputRange() As Range
'This is segregated because of how excel handles cancelling a range input
Dim userAnswer As Range
On Error GoTo inputerror
Set userAnswer = Application.InputBox("Please select a single column to parse", "Column Parser", Type:=8)
Set GetUserInputRange = userAnswer
Exit Function
inputerror:
Set GetUserInputRange = Nothing
End Function
Now in my main sub I can
dim someRange as range
set someRange = GetUserInputRange
if someRange is Nothing Then Exit Sub
Anyhow this is not the same as the accepted answer because it allows the user to only handle this error with a specific error handler and not need to resume next or have the rest of the procedure handled the same way. In case anyone ends up here like I did.
I have found that checking for the "Object required" error that you mentioned is one way of handling a cancel.
On Error Resume Next
dim selectRange as Range
' InputBox will prevent invalid ranges from being submitted when set to Type:=8.
Set selectRange = Application.InputBox("Select your range", "Hello", , , , , , 8)
' Check for cancel: "Object required".
If Err.Number = 424 Then
' Cancel.
Exit Sub
End If
On Error GoTo 0
I went with a cleaner solution:
Dim InputValue As Range
On Error Resume Next
Set InputValue = Application.InputBox("Select Range","Obtain Range", Type:=8)
Err.Clear
If InputValue Is Nothing Then
GoTo ExitApp:
End If
This will clear the error message and catch the "nothing" value returned to InputValue. Usefully, this doesn't interrupt a submission of no information, which Excel just loops back to requesting input automatically, but the user may need to add additional error handling for bad data entry.
Down code, add:
ExitApp:
Exit Sub
For exiting, which can be usefully shared between multiple input cancel handlers.
If I use Dirks second answer inside a for loop and I want to exit my sub, it is not enough to execute an Exit Sub inside his IF statement
I found that if I use Exit Sub standalone inside a for loop, I will not exit my sub in all cases, however, in most cases only exit the for loop.
Here you have Dirks code
EDIT
Another smart way is using the same behavior with a collection like
this:
Sub test()
Dim MyRange As Range
Dim MyCol As New Collection
MyCol.Add Application.InputBox("dada", , , , , , , 8)
If TypeOf MyCol(1) Is Range Then Set MyRange = MyCol(1)
Set MyCol = New Collection
If MyRange Is Nothing Then
Debug.Print "The input box has been canceled"
Else
Debug.Print "the range " & MyRange.Address & " was selected"
End If
End Sub
If you still have any questions, just ask ;)
Here is what I made to work as a example:
Sub test()
Dim i as Integer
Dim boolExit as Boolean
Dim MyRange As Range
Dim MyCol As New Collection
boolExit = False
For i = 1 To 5 Then
MyCol.Add Application.InputBox("dada", , , , , , , 8)
If TypeOf MyCol(1) Is Range Then Set MyRange = MyCol(1)
Set MyCol = New Collection
If MyRange Is Nothing Then
Debug.Print "The inputbox has been canceled"
boolExit = True
Exit Sub
Else
Debug.Print "the range " & MyRange.Address & " was selected"
End If
Next i
If boolExit = True Then Exit Sub 'Checks if Sub should be exited
Debug.Print "Program completed"
End Sub
If you press cancel at anytime in the five runs, the Sub is shutdown with the above code and you will never see Program completed printed.
However if you remove boolExit from the above, the code after the For loop is still being run if you press cancel in any of the 1+ runs and you will see Program completed even when that is not true.

Excel Error Handling for range object

I'm working on an Excel user form where the user can input a range. For example, they can put in "B5" and "B20".
I'm trying to do error handling to prevent the user from putting in an incorrect range. For Example, "asdf" and "fdsa".
The following code fails:
Private Sub cmdSend_Click()
Dim beginTerm As String
Dim endTerm As String
beginTerm = TermsBegin.Text
endTerm = TermsEnd.Text
If (IsError(Worksheets("Account Information").Range(beginTerm + ":" + endTerm)) = True) Then
MsgBox "Cell Range is invalid."
Exit Sub
End If
End Sub
I also tried the following:
Private Sub cmdSend_Click()
Dim beginTerm As String
Dim endTerm As String
beginTerm = TermsBegin.Text
endTerm = TermsEnd.Text
Dim myRange As Range
myRange = Worksheets("Account Information").Range(beginTerm + ":" + endTerm)
On Error GoTo ErrHandler
On Error GoTo 0
'other code ...
ErrHandler:
MsgBox "Cell Range is invalid."
Exit Sub
End Sub
My question is how can I handle the case that it fails?
Thanks!
You have to put
On Error GoTo ErrHandler
before the line that could throw the error.
If you need to get a range from a user, I would recommend using Application.InputBox with a Type = 8. This allows the user to select a range from the worksheet.
Check this out:
http://www.ozgrid.com/VBA/inputbox.htm
Also, if you are using a userform, you can also add a command button that will call the Application.InputBox to allow a user to select a range.
Quick example:
Private Sub CommandButton1_Click()
Dim r As Range
On Error Resume Next
Set r = Application.InputBox(Prompt:= _
"Please select a range with your Mouse to be bolded.", _
Title:="SPECIFY RANGE", Type:=8)
If Not r Is Nothing Then MsgBox r.Address
On Error GoTo 0
End Sub

Resources