我读了一些问题&关于这个问题的文章,但由于我是一个完全的初学者,我无法找到我的个人解决方案。
当用户在InputBox
表单上单击取消时,我需要退出sub。此外,我需要InputBox
接受输入值。
Dim UserCol As String
Dim FirstRow As Integer
UserCol = Application.InputBox(Prompt:="In what Column do we search? (E.g. enter: A)", Type:=2)
If UserCol = False Then Exit Sub
' On cancel works OK. But if you type "A" (no quotes) u get a run-time ERROR 13!
FirstRow = Application.InputBox(Prompt:="What is your data-table's first row? (E.g. enter: 2)", Type:=1)
If FirstRow = False Then Exit Sub
' On both cancel & input works flawlessly.
我尝试删除Type := 2
,但没有任何更改。
不能将字符串视为布尔值(您正在做的事情)。一个字符串可以输出一个真/假的结果,但不是你正在做的
Dim UserCol As String
Dim FirstRow As Integer
UserCol = Application.InputBox(Prompt:="In what Column do we search? (E.g. enter: A)", Type:=2)
If Len(Trim(UserCol)) < 1 Then Exit Sub
' On cancel works OK. But if you type "A" (no quotes) u get a run-time ERROR 13!
FirstRow = Application.InputBox(Prompt:="What is your data-table's first row? (E.g. enter: 2)", Type:=1)
If FirstRow < 1 Then Exit Sub
如果("修剪")输入字符串的长度小于1,则第一个条件为false(并且退出Sub
)。第二个条件,如果输入字符串不是数字。
注意:请记住,第二个条件不触发错误的原因是整数"支持布尔值";尽管它在这里没有任何真正的意义:如果你删除这个条件,一切都不会改变。我的条件检查您真正想要的内容(行大于或等于1)。还要记住,InputBox
支持整数,但通常情况并非如此(对于大多数此类控件,您必须将输入作为字符串,并将其转换为整数;明示或暗示)。
更新-
Coude to account for Cancel按钮点击:
Dim UserCol As String
Dim FirstRow As Integer
UserCol = Application.InputBox(Prompt:="In what Column do we search? (E.g. enter: A)", Type:=2)
If (LCase(UserCol) <> "false") Then
If Len(Trim(UserCol)) < 1 Then Exit Sub
' On cancel works OK. But if you type "A" (no quotes) u get a run-time ERROR 13!
FirstRow = Application.InputBox(Prompt:="What is your data-table's first row? (E.g. enter: 2)", Type:=1)
If (FirstRow < 1) Then Exit Sub
End If
如果第一个InputBox被取消,则返回一个"False"(作为字符串),如果第二个被取消,将返回一个0(因此原始条件可以处理此问题)。