tags:

views:

95

answers:

2

This is probably a simple question, but if I need to collect data at the start of a sub, using several input boxes, which one of these is the right way?

Example 1:

InputText1 = InputBox("Enter your name")  
If InputText1 = "" Then Exit Sub

InputText2 = InputBox("Enter your age")
If InputText2 = "" Then Exit Sub

'Do something

Example 2:

InputText1 = InputBox("Enter your name")  
If Not InputText1 = "" Then  
  InputText2 = InputBox("Enter your age")  
  If Not InputText2 = "" Then  
    'Do something  
  End If
End If
+3  A: 

I think a better way would be to create a form asking for all of the data.

However both your sets of code work. It depends on if you believe that there should only be one exit in a procedure. Your second example only has one exit. The reasoning for that is that you always know where it exits. However the downside is that the code becomes nested and more complex visually. I prefer to exit if he condition is simple and the subroutine is ending with an error exit ie not doing something. SO I would prefer Example 1.

Mark
+1: I agree, don't rely on InpputBoxes for input - you can't really perform restrictions on user answers (at least not in realtime). I agree with Mark that example 1 does look more understandable especially if you continue the trend with more InputBoxes
waqasahmed
I agree example 1 is better, but would stipulate that there shouldn't be much else happening in the routine - or that the exits should be really early in the routine. Exit points part way through a routine can be a source of errors if you allow the routine to become long and complex. (Long and complex routines are often a bad idea anyway but they are even worse if there are exits scattered throughout.)
MarkJ
Yes this comment from MarkJ expands what I meant to say instead
Mark
+1  A: 

Related item of interest that may not help answer your question:

There is another returned state you can test for: the Cancel button.

Dim InputText1 As String

InputText1 = InputBox("Enter your name")
If StrPtr(InputText1) = 0 Then
    MsgBox "*Canceled*"
ElseIf InputText1 = "" Then
    MsgBox "*Empty*"
Else
    MsgBox InputText1
End If

It may not matter in this case, but it can be useful to tell the difference.

Bob Riemersma
Another reason to use a form :)
Mark