Frage

I've read a few questions & articles about this issue, though since I'm a total beginner, I couldn't figure out my personal solution.

I need to exit sub when the user clicks cancel on the InputBox form. In adddition, I need the InputBox to accept the input value.

    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.

I tried to remove Type := 2 but there was no change.

War es hilfreich?

Lösung

You cannot treat strings as booleans (what you are doing). A string can output a true/false result but not as you are doing it. Try with this code:

  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

The first condition is false (and the Sub is exited) if the length of the ("trimmed") input string is lower than 1. The second condition, if the input string is not a number.

NOTE: bear in mind that the reason why the second condition does not trigger an error is because integers do "support boolean"; although it does not have any real meaning here: if you delete this condition nothing would change. My condition checks for what you really want (row being greater or equal than 1). Also remember that InputBox supports integers but this is not usually the case (with most of the controls of this type, you would have to get the inputs as string and convert them into integer; expressly or implicitely).

UPDATE -

Coude to account for Cancel-button clicks:

   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

If the first InputBox is cancelled a "False" is returned (as string) and if the second one is cancelled a 0 is returned (and thus the original condition can deal with that).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top