I'm working with excel vba since 3 month now and this is (after one course of programming in university) my first real contact to programming. Please take that to account.
I built up a userform with many textboxes. Therefore I wrote a makro which first checks if the user put in a value in every textbox so that afterwards the procedure begins. If there is not a value in every textbox I want the exit sub after msgbox the user to fill again every textbox. Quiet simple, right?
I thought the best way to manage this is using the Go to
-statement. After showing my boss the code he told me I should never use this statement to avoid some sort of spaghetti code. He told me a real programmer would never use this statement and would try to work his way around. This is what my code looks like:
Private Sub SaveButton_Click()
Dim i As Integer
'mandatory textboxes:
For i = 1 To 13
If UserForm1.Controls("Textbox" & i) = "" Then: GoTo again
Next
'procedure...
Exit Sub
again:
MsgBox "Please fill in every mandatory textbox"
End Sub
My question: is it right to avoid this statement in every situation? Is it really some sort of unspoken rule to never use that statement? What are the Pros and Cons of this, and which are my alternatives(especially in this case)?
I appreciate every helpful answer. Thank you!
Your code can be easily re-written as below:
Don't ever use
GoTo
unless it is behindOn Error …
or not avoidable. If there is any chance to avoidGoTo
, then avoid it. It makes your code hard to maintain and is considered to be a bad practice.As GSerg pointed out there might be rare cases where
GoTo
cannot be avoided. Eg. usingGoTo
for emulating missing language constructs (e.g. VBA lacks the Continue keyword) and exiting deeply nested loops prematurely.Could be rewritten thus. So below the goto is replace by an
Exit For
and then a subsequent test. Avoid goto unless in anOn Error Goto <lable>
statement.