相当于 Google Apps 脚本中的“GoTo”(相当于 VBA-GAS)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17153890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:41:59  来源:igfitidea点击:

Equivalent of "GoTo" in Google Apps Script (equivalent VBA-GAS )

javascriptexcel-vbagoogle-apps-scriptvbaexcel

提问by Frank Montemorano

When writing my VBA macros I often used "GoTo" so as to jump to a previous part of the macro without leaving the Sub. Now that I'm converting all my macros to Google Apps Script I'm trying to find the equivalent for “GoTo”.

在编写 VBA 宏时,我经常使用“GoTo”,以便在不离开 Sub 的情况下跳转到宏的前一部分。现在我正在将我所有的宏转换为 Google Apps 脚本,我试图找到“GoTo”的等效项。

Sub MySub()
Dim sheetname1 As String
Dim sheetname2 As String
On Error GoTo Err
       sheetname1 = ActiveSheet.Name
           Sheets.Add After:=Sheets(Sheets.Count)
           ActiveSheet.Name = "passwords"
       sheetname2 = ActiveSheet.Name
GoTo aftererr
Err:
MsgBox Error(Err)
Exit Sub
aftererr:

This is just one instance of my use of GoTo. However I need it for my new scripts in many other ways; not just for redirecting errors. For example:

这只是我使用 GoTo 的一个实例。但是,我在许多其他方面都需要它用于我的新脚本;不仅仅是为了重定向错误。例如:

 function MyFunction() {
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sh = ss.getActiveSheet();
 if(criteraA == criteraB){
 sh.offset(1,0).activate();
 var i=i + 1;
 //?? GoTo ??
 }else{
 var i=0;
 sh.getRange(row, column)(1,sr.offset(0,1).getColumn()).activate();
 }

采纳答案by Louis Ricci

You don't need GoTo, most people would argue that it is terrible programming practice to use it even when it is present. Using other control structures will do the job.

你不需要 GoTo,大多数人会争辩说,即使它存在,使用它也是可怕的编程实践。使用其他控制结构将完成这项工作。

if() {
} else if() {
} else {
}

for(;;) {
   continue;
   break;
}

while() {
}

do {
} while();

switch() {
case:
default:
}

// for errors
throw "Error string"

try {
} catch(error) {
}

You'll have to shuffle your logic around a bit, but it will result is better more maintainable code.

您将不得不稍微调整一下您的逻辑,但这会导致更好的更易于维护的代码。