4

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”.

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:

 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();
 }
Community
  • 1
  • 1
Frank Montemorano
  • 321
  • 4
  • 6
  • 12

1 Answers1

4

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.

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.

Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
  • It's a strong and extremist religion what is against using GoTo or jump to a label. Look at the tricks programmers do to simulate a goto. – Richard de Ree Oct 23 '16 at 09:52
  • @Richard - If your goal is to create source code that programmers of varying skill level can maintain and add onto then GOTO is a relic of an ambiguous/spaghetti-code past. The WHILE, FOR, IF ELSE, DO WHILE constructs compile to the GOTO (opcode: JMP label), and/or a comparison and conditional GOTO (opcode: CMP + J[cnd] label) at the processor level; not being able to conform to those constructs is just a failing of the programmer to adapt to the language. Unless your code is very time critical, letting the compiler do the optimization work, so that your code is clear and readable seems best. – Louis Ricci Oct 24 '16 at 15:20