Excel VBA取消输入框不返回false / exit子

时间:2015-08-03 18:24:28

标签: excel vba excel-vba inputbox

我的Excel工作表上有一个命令按钮,用于打开application.inputbox,预先加载当前选定的范围,并将该范围内的单元格内容附加到对这些单元格的注释中。

我正在使用if / else语句检查是否单击了取消按钮,但是它没有退出sub;无论我单击确定还是取消,代码都会运行。我认为取消按钮不会返回'false'或我的if语句被破坏。

以下是代码:

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

2 个答案:

答案 0 :(得分:3)

WorkRng已被声明为范围。

更改

If WorkRng = False Then

If WorkRng is nothing Then

将您的代码更改为

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

答案 1 :(得分: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