了解GoTo语句的优缺点 [英] Understand the pro and cons of the GoTo statement

查看:203
本文介绍了了解GoTo语句的优缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自3个月以来,我一直在使用excel vba,这是(大学的一门编程课程之后)我第一次真正接触编程.请考虑到这一点.

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.

我建立了一个包含许多文本框的用户窗体.因此,我编写了一个Makro,它首先检查用户是否在每个文本框中都输入了一个值,以便随后开始该过程.如果每个文本框中都没有值,我希望msgbox之后的exit子用户再次填充每个文本框.安静很简单,对吧?

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?

我认为管理此问题的最佳方法是使用Go to语句.向老板展示了代码后,他告诉我,我绝对不要使用此语句来避免使用意大利面条式的代码.他告诉我真正的程序员永远不会使用此语句,而是会努力解决.这是我的代码:

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:

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

切勿使用GoTo,除非它在On Error …之后或无法避免.如果有机会避免使用GoTo,请避免使用它.它使您的代码难以维护,被认为是不好的做法.

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.

正如GSerg所指出的,在极少数情况下,无法避免GoTo.例如.使用GoTo模拟缺少的语言构造(例如,VBA缺少继续关键字)并过早退出深层嵌套的循环.

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.

这篇关于了解GoTo语句的优缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆