Excel VBA取消输入框不返回false/exit sub
Posted
技术标签:
【中文标题】Excel VBA取消输入框不返回false/exit sub【英文标题】:Excel VBA cancelling input box does not return false/exit sub 【发布时间】:2015-10-25 23:12:52 【问题描述】:我的 Excel 工作表上有一个命令按钮,它打开一个 application.inputbox,预加载当前选定的范围,并将该范围内单元格的内容附加到这些单元格的注释中。
我正在使用 if/else 语句来检查是否单击了取消按钮,但它没有退出子程序;无论我单击“确定”还是“取消”,代码都会运行。我认为取消按钮没有返回“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
【问题讨论】:
【参考方案1】: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
【讨论】:
我试过了,但它没有用 - 没有任何东西被自动更正为 Nothing 并且代码的行为方式与以前相同。可能是因为输入框自动加载了一个范围吗?我通过使用带有 vbYesNo 的消息框并检查是,解决了我的问题,但仍然想知道为什么我的第一个代码不起作用 检查更新的代码。您可能需要刷新页面。【参考方案2】:Dim sRange As String
sRange = Application.InputBox("Range", xTitleId, Application.Selection.Address)
Is sRange = "" Then
Exit Sub
Else
Set WorkRng = Range(sRange)
End If
【讨论】:
以上是关于Excel VBA取消输入框不返回false/exit sub的主要内容,如果未能解决你的问题,请参考以下文章