How to identify between ok and cancel button in inputbox

前端 未结 3 1620
情歌与酒
情歌与酒 2020-12-03 19:54

Hi Hi I have to write a code where if the user clicks enters something in the input box it should proceed further.If it doesnot enter any value it should throw back the same

相关标签:
3条回答
  • 2020-12-03 20:17

    You need to deal with (at least) three cases - InputBox() returns:

    1. an empty value (Empty, vbEmpty) because the user pressed Cancel or closed the dialog
    2. an empty string ("") or a string of blanks (" ")
    3. a (hopefully) valid string

    In code:

    Option Explicit
    
    Do While True
       Dim vInp : vInp = InputBox("ee")
       WScript.Echo TypeName(vInp)
       Select Case True
         Case IsEmpty(vInp)
           WScript.Echo "Abort"
           Exit Do
         Case "" = Trim(vInp)
           WScript.Echo "Try again"
         Case Else
           WScript.Echo "Work with " & vInp
           Exit Do
       End Select
    Loop
    

    sample output:

    String
    Try again
    Empty
    Abort
    
    String
    Work with aaa
    

    Sorry to say, but the Docs just lie:

    If the user clicks OK or presses ENTER, the InputBox function returns whatever is in the text box. If the user clicks Cancel, the function returns a zero-length string ("").

    It should be:

    ... If the user clicks Cancel, the function returns an empty value (TypeName Empty, VarType vbEmpty).

    0 讨论(0)
  • 2020-12-03 20:22

    I'm using VBS and my investigation into cancel/ok revealed the following:

    Cancel returns an empty string AND a zero length string - same thing you say?, apparently not.

    Ok returns a zero length string only.

    I use the code below to differentiate.

       if IsEmpty(nmbr)  then               'cancel button pressed ?
            nmbr = "x"  
       end if  
    
       if not IsEmpty(nmbr) then            'ok button pressed ?
          if len(nmbr) = 0 then
            nmbr = "ok"
          end if 
       end if
    
    0 讨论(0)
  • 2020-12-03 20:40

    For InputBox(), you can use the default value to determine if the user clicked Cancel or if they clicked OK or hit Enter to continue without entering a value:

    Sub Get_TIN()
       TIN = Trim(InputBox("Enter the provider TIN:", "Provider TIN", "ex. 123456789"))
    
       If TIN = "" Then    'When CANCEL is clicked because "TIN" will be empty.
          MsgBox "You pressed Cancel. Program will now end.", vbExclamation + vbOKOnly, "Macro End"
          Exit Sub
       End If
    
       If IsEmpty(TIN) = False Then     'When OK is clicked or Enter pressed because default text will be stored. Next, set TIN to "".
          TIN = ""
       End If
    End Sub
    
    0 讨论(0)
提交回复
热议问题