3
votes

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();
 }
1

1 Answers

4
votes

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.