vba inputBox: How to tell difference between “cancel” and “OK” with an empty textbox

风流意气都作罢 提交于 2020-04-18 05:01:06

问题


A vba inputBox returns an empty string when the cancel button is pressed. When OK is pressed, it returns whatever text is in its textbox. The inputBox's third positional argument is the initial text in its textbox. The default value for this argument is "".

In my application, I use an inputBox to ask a user to specify the name for a new record when he clicks an "Add Record" button. If he presses "cancel", no problem: seems he changed his mind about that new record. I exit the sub.

However, if he fails to enter a name, or enters one and deletes it, I want to NOT accept that and instead use a msgBox to tell him he must specify a unique record name.

However, it seems that with vba inputBox it is not straight forward to tell the difference between "cancel" and "OK" with an empty textbox. I'd like to find out how to do that.

While looking for an answer, I found several questions similar to this one, but none had a complete enough answer to solve my problem.


回答1:


There is a way to check if user clicked "Cancel" or just entered empty string. Try this:

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

However it is quite sketchy solution. You can read more about StrPtr function here: What are the benefits and risks of using the StrPtr function in VBA?




回答2:


I believe that the code below will provide you a robust solution that works. More information the Application.InputBox method and function can be found at 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


来源:https://stackoverflow.com/questions/52181431/vba-inputbox-how-to-tell-difference-between-cancel-and-ok-with-an-empty-tex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!