I have the following piece of code:
dim selectRange as Range
Set selectRange = Application.InputBox(\"Select your range\", \"Hello\", , , , , , 8)
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.