【问题标题】:How to tell the difference between "cancel" and "OK" with an empty textbox of an InputBox?如何用 InputBox 的空文本框区分“取消”和“确定”?
【发布时间】:2018-09-05 09:15:23
【问题描述】:

按下取消按钮时,VBA 输入框会返回一个空字符串。
当按下 OK 时,它的文本框中的文本。
inputBox 的第三个位置参数是其文本框中的初始文本。此参数的默认值为 ""。

当用户单击“添加记录”按钮时,我使用输入框要求用户指定新记录的名称。如果他按“取消”,我退出子。

如果他没有输入名称,或者输入了一个并删除了它,我想要一个 msgBox 告诉他他必须指定一个唯一的记录名称。

如何区分空文本框的“取消”和“确定”?

我发现了几个类似的问题,但没有一个能解决我的问题。

【问题讨论】:

  • 你能告诉我们你到目前为止所做的尝试吗?
  • @JamieRiis,我发现真正区分差异的唯一方法是下面 Kirzsu 的建议。另一种可能性是使用第三个位置参数指定默认值" ",然后我可以检查返回值是否等于" "(按下输入)或""(按下取消) ,但不能保证用户不会只是删除默认值然后按 OK...

标签: vba input user-controls


【解决方案1】:

有一种方法可以检查用户是单击“取消”还是只是输入了空字符串。 试试这个:

test = InputBox("Enter a value")
If StrPtr(test) = 0 Then
    MsgBox "Cancel"
ElseIf Len(test) = 0 Then
    MsgBox "No entry"
Else
    MsgBox "Correct"
End If

然而,这是一个相当粗略的解决方案。您可以在此处阅读有关 StrPtr 函数的更多信息: What are the benefits and risks of using the StrPtr function in VBA?

【讨论】:

  • 谢谢,这解决了我的问题。但是,正如您所说:这有点粗略。如果到时候我没有更好的答案,我会把这个标记为答案。
【解决方案2】:

我相信下面的代码将为您提供一个有效的强大解决方案。有关 Application.InputBox 方法和函数的更多信息,请访问Microsoft Docs

Option Explicit

'Type Parameter of the Application.InputBox method tells
'the method to return a value of that type.  Below I've shown
'having it return a text string
Public Const A_TEXT_STRING As Variant = 2

Sub Button1_Click()
    Dim myVal As Variant

    myVal = Application.InputBox("Enter Record Name", _
                           Title:="RECORD NAME", _
                           Type:=A_TEXT_STRING)
    'If myVal equals the vbNullString type then
    'the person pressed OK without entering any data
    If myVal = vbNullString Then
        MsgBox "Please Select a record", Buttons:=vbOKOnly, Title:="SELECT RECORD"
    'if myVal is equal to False (boolean value) then the user pressed
    'the Cancel button.  By checking for not equal, that means that the user pressed
    'Ok and entered a value.  You'll need to handle the condition of valid values
    ElseIf myVal <> False Then
        Range("A1").Value2 = myVal
    End If
End Sub

【讨论】:

    【解决方案3】:

    感谢您一直以来对我的帮助……您来了。在这种情况下,是 YES 和 NO 的文本框。如果你想确定并取消,你将不得不看到这个: 我的情况是 vbYesNo, 你的情况是 vbOKCancel OK 返回值为:1 取消返回值为:2

    Dim control As String
    control = Empty
    
    control = MsgBox("Are you sure ??", vbYesNo, "System warning")
    If control = 6 Then
        ' code if answer was YES
    ElseIf control = 7 Then
        ' code if answer was NO
    End If
    

    【讨论】:

    • 这并不能真正回答问题。如果您有其他问题,可以点击 提问。要在此问题有新答案时收到通知,您可以follow this question。一旦你有足够的reputation,你也可以add a bounty 来引起对这个问题的更多关注。 - From Review
    猜你喜欢
    • 1970-01-01
    • 2011-06-21
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多