2

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
MichaelV
  • 25
  • 7

2 Answers2

3

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
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
  • I tried this and it did not work - nothing was autocorrected to Nothing and the code behaved in the same way as before. Could it be because the inputbox is automatically loaded with a range? I fixed my issue by using a message box with vbYesNo and checking for yes, but still would like to know why my first code didn't work – MichaelV Aug 03 '15 at 18:44
  • Check the updated code. You may have to refresh the page. – Siddharth Rout Aug 03 '15 at 18:50
1
Dim sRange As String

sRange = Application.InputBox("Range", xTitleId, Application.Selection.Address)
Is sRange = "" Then
    Exit Sub
Else
    Set WorkRng = Range(sRange)
End If
Don Jewett
  • 1,867
  • 14
  • 27