MichaelV
MichaelV

Reputation: 25

Excel VBA cancelling input box does not return false/exit sub

I have a command button on my Excel sheet which opens an application.inputbox, preloaded with the currently selected range, and appends the contents of the cells in that range to a comment on those cells.

I am using an if/else statement to check if the cancel button is clicked, but it is not exiting the sub; the code runs whether I click OK or Cancel. I think either the cancel button is not returning 'false' or my if statement is broken.

Here is the code:

Private Sub CommentLogButton_Click()
'This Sub Appends Cell Contents to Cell Comment
Dim rng As Range
Dim WorkRng As Range
On Error Resume Next
xTitleId = "Range to Log"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
If WorkRng = False Then
    Exit Sub
Else
    For Each rng In WorkRng
        rng.NoteText Text:=rng.NoteText & rng.Value & ", "
        rng.Value = ""
    Next
End If
End Sub

Upvotes: 2

Views: 2229

Answers (2)

Siddharth Rout
Siddharth Rout

Reputation: 149335

WorkRng has been declared as range.

Change

If WorkRng = False Then

to

If WorkRng is nothing Then

Change your code to

Private Sub CommentLogButton_Click()
    'This Sub Appends Cell Contents to Cell Comment
    Dim rng As Range, WorkRng As Range
    Dim rngAddress As String

    xTitleId = "Range to Log"

    '~~> Check if what the user selected is a valid range
    If TypeName(Selection) <> "Range" Then
        MsgBox "Select a range first."
        Exit Sub
    End If

    rngAddress = Application.Selection.Address

    On Error Resume Next
    Set WorkRng = Application.InputBox("Range", xTitleId, rngAddress, Type:=8)
    On Error GoTo 0

    If WorkRng Is Nothing Then
        Exit Sub
    Else
        For Each rng In WorkRng
            rng.NoteText Text:=rng.NoteText & rng.Value & ", "
            rng.Value = ""
        Next
    End If
End Sub

Upvotes: 3

Don Jewett
Don Jewett

Reputation: 1977

Dim sRange As String

sRange = Application.InputBox("Range", xTitleId, Application.Selection.Address)
Is sRange = "" Then
    Exit Sub
Else
    Set WorkRng = Range(sRange)
End If

Upvotes: 1

Related Questions