问题
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!
回答1:
Your code can be easily re-written as below:
Private Sub SaveButton_Click()
Dim i As Integer
'mandatory textboxes:
For i = 1 To 13
If UserForm1.Controls("Textbox" & i) = "" Then
MsgBox "Please fill in every mandatory textbox"
Exit Sub
End If
Next
End Sub
Don't ever use GoTo
unless it is behind On Error …
or not avoidable. If there is any chance to avoid GoTo
, 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. using GoTo
for emulating missing language constructs (e.g. VBA lacks the Continue keyword) and exiting deeply nested loops prematurely.
回答2:
Could be rewritten thus. So below the goto is replace by an Exit For
and then a subsequent test. Avoid goto unless in an On Error Goto <lable>
statement.
Private Sub SaveButton_Click()
Dim i As Integer
Dim bGut As Boolean: bGut = True
'mandatory textboxes:
For i = 1 To 13
If UserForm1.Controls("Textbox" & i) = "" Then
bGut = False
Exit For '* skip out
End If
Next
If Not bGut Then
MsgBox "Please fill in every mandatory textbox"
Else
'* start processing
End If
End Sub
来源:https://stackoverflow.com/questions/54178768/understand-the-pro-and-cons-of-the-goto-statement