Correggere gli errori nel codice convertito

Il componente aggiuntivo Macro Converter automatizza gran parte del processo di conversione, ma potrebbe essere necessario apportare modifiche ad alcune API e altri elementi per finalizzare il codice.

Utilizza questa guida per comprendere i file Apps Script (file GS) aggiunti al tuo progetto, interpretare i diversi tipi di errore e scoprire come correggerli.

Informazioni sui file Apps Script aggiunti al progetto

Al tuo progetto Apps Script vengono aggiunti altri file GS per:

  • Definisci le costanti e i valori VBA che non esistono in Apps Script.
  • Implementa le API non convertite.
  • Risolvi le varianti.

I seguenti file GS vengono aggiunti al progetto Apps Script:

  • Library.gs
  • Unimplemented_constructs.gs
  • Variant_resolutions.gs

Library.gs

In generale, non è necessario apportare modifiche al file library.gs.

Il file library.gs definisce funzioni e costanti utilizzate nel codice VBA che non esistono in Apps Script. In questo modo il nuovo codice Apps Script simile al tuo codice VBA. Inoltre, non è necessario ripetere le definizioni ogni volta che vengono utilizzate le funzioni o le costanti del file library.gs.

Unimplemented_constructs.gs

Il file unimplemented_constructs.gs indirizza i costrutti o le API che non è stato possibile convertire da Macro Converter. Probabilmente dovrai modificare il file per far funzionare il codice come previsto.

Esempio: Window.Activate()

Di seguito è riportato un esempio di API non supportata denominata Window.Activate(). Il convertitore Macro crea una nuova funzione Apps Script con un nome simile e la definisce nel file unimplemented_constructs.gs. Poiché la funzione VBA non è supportata, la nuova funzione Apps Script genera un'eccezione.

La nuova funzione viene aggiunta al codice Apps Script convertito ovunque sia stata utilizzata l'API originale nel codice VBA.

Se trovi una soluzione alternativa per ricreare il comportamento dell'API originale, devi solo aggiornare la definizione della funzione nel file unimplemented_constructs.gs. Una volta definita nella pagina, la funzione viene applicata ovunque venga visualizzata nel progetto Apps Script.

Ecco l'esempio nel codice:

Codice VBA originale

Window.activate()

Codice Apps Script convertito, aggiunto in linea

_api_window_activate();

Definizione della funzione aggiunta al file unimplemented_constructs.gs

/**
 * Could not convert window.activate API. Please add relevant code in the
 * following function to implement it.
 * This API has been used at the following locations in the VBA script.
 *     module1 : line 3
 *
 * We couldn't find an equivalent API in Apps Script for this VBA API. Please
 * reconsider if this function call is critical, otherwise consider implementing
 * it in a different way.
 */
function _api_window_activate(CallingObject) {
  ThrowException("API window.activate not supported yet.");
}

Variant_resolutions.gs

Il file variant_resolutions.gs viene aggiunto al progetto Apps Script se non è possibile determinare il tipo di oggetto. Questo può accadere per diversi motivi, ad esempio un'API con più tipi restituiti o l'oggetto dichiarato come una variante stessa.

Macro Converter aggiunge a questo file una nuova funzione denominata __handle_resolve_<api>() che sostituisce l'API in questione e consente di determinare il tipo di oggetto.

In alcuni casi, potrebbe essere necessario aggiornare la funzione __handle_resolve_<api>() per dichiarare manualmente il tipo di oggetto. Vedi Tipo di oggetto non supportato.

Esempio: name()

Molti tipi di oggetti in VBA definiscono un'API name(). In genere, l'equivalente di Apps Script è getName(), ma non per tutti i tipi di oggetto. Possono verificarsi più casi alternativi:

  • L'API equivalente dell'oggetto ha un nome diverso da getName().
  • L'oggetto non dispone di un'API Apps Script per ottenere il nome.
  • Non esiste un oggetto Apps Script equivalente.

Quando non viene determinato il tipo di oggetto, Macro Converter crea una nuova funzione denominata __handle_resolve_name nel file variant_resolutions.gs.

Ecco l'esempio nel codice:

Codice VBA originale

a = Selection.name

In questo caso, l'API name() viene richiamata nella selezione corrente. La selezione può essere un oggetto Fogli o un oggetto Shape. Se si tratta di un oggetto Fogli, la traduzione è getName(), ma se è un oggetto Shape, non esiste un equivalente in Apps Script.

Codice Apps Script convertito, aggiunto in linea

a = __handle_resolve_name({}, getActiveSelection(), {});

La funzione __handle_resolve_name() riportata di seguito viene aggiunta al file variant_resolution.gs per risolvere diversi tipi di oggetti. La funzione controlla il tipo di oggetto, quindi utilizza getName() se è supportato o restituisce un errore se getName() non è supportato.

Definizione della funzione aggiunta al file variant_resolution.gs

function __handle_resolve_name(ExecutionContext, CallingObject, params_map) {
  var found_api_variant = false;
  var return_value;
  if (String(CallingObject) == "Sheet") {
    if (!ExecutionContext.isLhs) {
      return_value = CallingObject.getName();
      found_api_variant = true;
    }
  }
  if (CallingObject instanceof ChartInSheet) {
    if (!ExecutionContext.isLhs) {
      return_value = CallingObject.getName();
      found_api_variant = true;
    }
  }
  if (!found_api_variant) {
    ThrowException("API .name not supported yet.");
  }
  return return_value;
}

Trovare errori

Quando si verifica un errore nel codice Apps Script convertito, il messaggio specifica il tipo di errore e la relativa posizione. Il formato del messaggio di errore dipende dal runtime di Apps Script in uso.

Se utilizzi il runtime V8 predefinito, verrà visualizzato un errore simile al seguente:

_api_windows_active (unimplemented_constructs:2:3)

Questo significa che l'errore si trova nel file unimplemented_constructs.gs alla riga 2, carattere 3.

Se utilizzi il runtime Rhino deprecato, verrà visualizzato un errore simile al seguente:

unimplemented_constructs:2 (_api_windows_active)

Questo significa che l'errore si trova nel file unimplemented_constructs.gs alla riga 2.

Tipi di errore

Puoi correggere la maggior parte degli errori riscontrati nei file unimplemented_constructs.gs e variant_resolution.gs descritti sopra.

I tipi di errori che potresti riscontrare includono:

API non implementata

Un'API non implementata è un'API che il convertitore macro non può convertire da VBA ad Apps Script e non esiste una soluzione alternativa nota per l'API.

Le API non implementate vengono in genere aggiunte al file unimplemented_constructs.gs come funzioni vuote, a volte con firme vuote. Se non è stato possibile determinare il tipo di oggetto, l'API non implementata potrebbe essere aggiunta al file variant_resolution.gs.

Nel report sulla compatibilità generato prima della conversione, questa API è etichettata come Richiede ulteriori indagini.

Se non correggi questo tipo di API nel tuo codice VBA prima di convertire il file, ecco come apparirà nel progetto Apps Script:

/**
* Could not convert . Please add relevant code in the following
* function to implement it.
* This API has been used at the following locations in the VBA script.
*      : 
* We couldn't find an equivalent API in Apps Script for this VBA API. Please
* reconsider if this function call is critical, otherwise consider implementing
* it in a different way.
* @param param1 {}
* @param param2 {}
* ...
* @return {}
*/
function _api_(param1, param2, ....) {
  ThrowException("API  not supported yet.");
}

Correggi gli errori dell'API non implementati

Definisci l'API non implementata con le API Apps Script o le librerie JS esistenti. Per farlo, segui questi passaggi:

  1. Apri il codice Apps Script convertito nel punto in cui si trova l'errore. Consulta la sezione Trovare errori.
  2. Sopra la funzione, leggi il commento che è stato aggiunto. In alcuni casi, il commento suggerisce come implementare l'API in Apps Script.
  3. Se non riesci a trovare un modo per implementare l'API in Apps Script, valuta la possibilità di rimuoverla dal tuo codice.
  4. Se non trovi una soluzione alternativa o rimuovi questa API dal codice e la macro genera questo errore, non puoi convertire questa macro.

Esempi di errori dell'API non implementati

Di seguito sono riportati alcuni esempi di scenari API non implementati e le relative soluzioni:

Esempio 1: nessun Apps Script equivalente o API sconosciuta

In questo esempio, Chart.Protect non è stato convertito automaticamente perché non esiste un modo per proteggere un grafico in Fogli Google.

/**
* Could not convert chart.protect API. Please add relevant code in the following
* function to implement it.
*
* This API has been used at the following locations in the VBA script.
*     sheet1 : line 3
* You can use the following Apps Script APIs to convert it.
*
* Comments : Auto conversion of Chart.Protect is not supported yet. If the API is
* critical for the workflow the user can implement the unimplemented handler
* method in the generated code, else comment out the throw statement.
*
* @param {Object} CallingObject represents the parent object using which the API
* has been called.
* @param {string} Password
* @param {boolean} DrawingObjects
* @param {boolean} Contents
* @param {boolean} Scenarios
* @param {boolean} UserInterfaceOnly
*
*/
function _api_chart_protect(
   CallingObject, Password, DrawingObjects, Contents, Scenarios,
   UserInterfaceOnly) {
 ThrowException('API chart.protect not supported yet.');
}
Anche se non puoi proteggere un grafico, puoi proteggere l'intervallo di dati del grafico in modo che non sia possibile modificare i dati.

Di seguito è riportata un'implementazione di esempio della protezione dell'intervallo:
/**
* Could not convert chart.protect API. Please add relevant code in the following
* function to implement it.
* This API has been used at the following locations in the VBA script.
*     sheet1 : line 3
*
* You can use the following Apps Script APIs to convert it.
* Comments : Auto conversion of Chart.Protect is not supported yet. If the API
* is critical for the workflow the user can implement the unimplemented handler
* method in the generated code, else comment out the throw statement.
*
* @param {Object} CallingObject represents the parent object using which the API
* has been called.
* @param {string} Password
* @param {boolean} DrawingObjects
* @param {boolean} Contents
* @param {boolean} Scenarios
* @param {boolean} UserInterfaceOnly
*/
function _api_chart_protect(
  CallingObject, Password, DrawingObjects, Contents, Scenarios, UserInterfaceOnly) {
var ranges = CallingObject.getChart().getRanges();
for (var i = 0; i < ranges.length; i++) {
  // Note that this does not lock the range for the document owner.
  ranges[i].protect();
}
}
Esempio 2: tipo di oggetto non supportato

Quando il tipo di oggetto è sconosciuto, l'errore dell'API non implementato viene aggiunto al file variant_resolution.gs. L'esempio riportato di seguito espande l'esempio dell'API name() VBA riportato sopra. Visita la pagina variant_resolution.gs.

In questo esempio, scoprirai:

  1. Come viene convertita l'API name() in una nuova funzione nel file variant_resolution.gs.
  2. Come viene chiamata la nuova funzione nel codice convertito.
  3. Come creare una soluzione alternativa per CommandBar, un tipo di oggetto non supportato, in Apps Script.

1. Poiché il codice convertito non può determinare il tipo di oggetto esatto su cui viene chiamato name(), Macro Converter crea una nuova funzione chiamata __handle_resolve_name, mostrata di seguito.

function __handle_resolve_name(ExecutionContext, CallingObject, params_map) {
 var found_api_variant = false;
 var return_value;
  if (String(CallingObject) == "Sheet") {
    if (!ExecutionContext.isLhs) {
      return_value = CallingObject.getName();
      found_api_variant = true;
    }
  }
  if (CallingObject instanceof ChartInSheet) {
    if (!ExecutionContext.isLhs) {
      return_value = CallingObject.getName();
      found_api_variant = true;
    }
  }
  if (!found_api_variant) {
    ThrowException('API .name not supported yet.');
  }
  return return_value;
}

2. Supponiamo che il codice VBA definisca una funzione PrintName() che chiama l'API name(). Il codice VBA è mostrato di seguito:

‘Defining a function that prints the name of the object in parameter
Sub PrintName(obj as Variant)
  Debug.Print obj.Name
End Sub
Poiché "name()" viene chiamato su un oggetto che è una variabile, il codice convertito non conosce il tipo di oggetto al momento della conversione. Il codice Apps Script convertito chiamerà la funzione "__handle_resolve_name":
function PrintName(obj) {
  Logger.log(_handle_resolve_name(obj));
}

3. Supponiamo che il tuo codice VBA chiami la funzione PrintName() sul tipo di oggetto CommandBar. Il codice VBA è mostrato di seguito:

PrintName Application.CommandBars.item("Standard")
CommandBar non è supportato in Apps Script e, di conseguenza, non sono supportati neanche i due metodi utilizzati nel codice VBA riportato sopra.
  • Application.CommandBars(): in VBA, restituisce un elenco di tutti CommandBar gli oggetti.
  • CommandBars.item(): in VBA, restituisce un oggetto CommandBar specifico.
Poiché questo tipo di oggetto non è supportato in Apps Script, il codice convertito crea le seguenti funzioni nel file "unimplemented_constructs.gs" che devi definire.
  • _api_application_commandbars()
  • _api_commandbars_item()
Le funzioni vengono richiamate nel codice convertito, come mostrato di seguito:
PrintName(_api_commandbars_item(_api_application_commandbars(), "Standard")))

Here’s how the new functions are added to the unimplemented_construct.gs file:

function _api_application_commandbars(CallingObject) {
  ThrowException('API application.commandbars not supported yet.');
}
function _api_commandbars_item(CallingObject, index) {
  ThrowException('API commandbars.item not supported yet.');
}

Per far funzionare le nuove funzioni, segui questi passaggi:

3.1 Definisci un nuovo tipo di oggetto che crei le funzionalità di CommandBars e una nuova raccolta di CommandBars simile a quella esistente in VBA.

3.2 Aggiungi un metodo getName() per il nuovo tipo di oggetto.

I passaggi 3.1 e 3.2 sono mostrati nel codice seguente. Gli oggetti Menu vengono creati come nuovo tipo di oggetto che riproduce il comportamento di CommandBars.

// Our Implementation of CommandBar using Menu objects.

function CommandBar(name) {
  this.name = name;
  // Create a menu object to represent the commandbar.
  this.menu = SpreadsheetApp.getUi().createMenu(name);
  // Create methods for retrieving or updating the name of the object
  this.getName = function() {
    return this.name;
  };
  this.updateName = function(name) {
    this.name = name;
  };
  // ========================================================================
  // Implement other methods of CommandBar objects that are used in the script.
  // =====================================================================
  return this;
}
// Our implementation of the collection of CommandBars that exists in VBA
function CommandBars() {
  this.commandBars = [];
  this.getCommandBar = function(name) {
    for (var i = 0; i < this.commandBars.length; i++) {
      if (!this.commandBars[i].getName() == name) {
        return this.commandBars[i];
      }
    }
    // No commandBar with the name exists, create a new one and return.
    var commandBar = new CommandBar(name);
    this.commandBars.push(commandBar);
    return commandBar;
  };
  return this;
}
// Create a global object that represents CommandBars collection.
var GlobalCommandBars = new CommandBars();

3.3 Modifica la funzione __handle_resolve_name nel file variant_resolution.gs per gestire il nuovo tipo di oggetto. Aggiungi una sezione alla funzione, come mostrato di seguito:

function __handle_resolve_name(ExecutionContext, CallingObject, params_map) {
 var found_api_variant = false;
 var return_value;
 if (String(CallingObject) == "Sheet") {
   if (!ExecutionContext.isLhs) {
     return_value = CallingObject.getName();
     found_api_variant = true;
   }
 }
 if (CallingObject instanceof ChartInSheet) {
   if (!ExecutionContext.isLhs) {
     return_value = CallingObject.getName();
     found_api_variant = true;
   }
 }
 // New section added below
 // ========================================================================
 if (CallingObject instanceof CommandBar) {
   objectExtend(params_map, {VALUETOSET: params_map.param0});
   if (ExecutionContext.isLhs) {
     // Call the setter method.
     CallingObject.updateName(params_map.VALUETOSET);
     found_api_variant = true;
   } else {
     // Getter is called, return the commandbar name,
     return_value = CallingObject.getName();
     found_api_variant = true;
   }
 }
 // ========================================================================
 // New section added above
 if (!found_api_variant) {
   ThrowException('API .name not supported yet.');
 }
 return return_value;
}

3.4 Definisci le due funzioni create nel file unimplemented_constructs.gs (_api_application_commandbars(), _api_commandbars_item()). Questo passaggio garantisce che le chiamate originali della funzione funzionino.

//This is straightforward based on the implementation of a CommandBar and the
// CommandBars collection above:
function _api_application_commandbars(CallingObject) {
 return GlobalCommandBars;
}
function _api_commandbars_item(CallingObject, index) {
 return CallingObject.getCommandBar(index);
}

Costrutti del linguaggio non implementati

Un construct è un elemento del linguaggio del codice che controlla il flusso di esecuzione o la visualizzazione dei dati. ad esempio loop, etichette, eventi e goto. Ecco un elenco di tutti i costrutti VBA.

I costrutti che il convertitore di macro non può convertire sono considerati costrutti del linguaggio non implementati.

Quando il convertitore macro determina che esiste un costrutto del linguaggio non implementato, inserisce un commento TODO.

I seguenti costrutti VBA non sono supportati:

Correggi gli errori di costrutto del linguaggio non implementati

  1. Aggiorna il codice in modo che la logica non si basi sulla struttura di un linguaggio non supportato.
  2. Apri il codice Apps Script convertito nel punto in cui si trova l'errore. Vedi Trovare errori.
  3. In base alla logica del codice, aggiornalo in modo che non richieda il costrutto del linguaggio non supportato.
  4. Se non riesci a trovare un modo per riscrivere il codice senza la struttura del linguaggio non supportato, non puoi convertire questa macro.

Esempi di errori di costrutto del linguaggio non implementati

Uno dei costrutti del linguaggio non implementati più comuni è un'istruzione GoTo. Puoi sostituire alcune istruzioni GoTo VBA con loop. Di seguito sono riportati due esempi di utilizzo dei loop al posto delle istruzioni GoTo.

Esempio 1: sostituisci GoTo con While Loop

Codice VBA originale
Sub Test()
 a = 0
 start: Debug.Print a
 While a < 100
   a = a + 1
   If a Mod 3 == 0
     Goto start
   End If
 Wend
End Sub
Codice Apps Script equivalente
function test() {
 var a = 0;
 start: do {
   console.log(a);
   while (a < 100) {
     a = a + 1;
     if (a % 3 == 0) {
       continue start;
     }
   }
   break start;
 } while (true);
}

Esempio 2: sostituire GoTo con For Loop

Codice VBA originale
Sub Test()
 a = 0
 For i = 1 to 100
   For j = 1 to 10
     a =a a + 1
     If i + j > 50
       GoTo endLoop
     End If
   Next j
 Next i
 endLoop: MsgBox a
End Sub
Codice Apps Script equivalente
function test() {
 var a = 0;
 endLoop: for (var i = 1; i <= 100; i++) {
    for  (var j = 0; j <=10; j++) {
      If (i + j > 50) {
        break endLoop;
      }
    }
 }
 Browser.msgBox(a);
}

   break start;
 } while (true);
}

API parzialmente supportata

Per le API parzialmente supportate, alcuni parametri di input sono supportati in Apps Script e altri no.

Ad esempio, l'API VBA legend_position viene utilizzata per definire la legenda in un grafico di Excel. Supporta diversi tipi di valori di input, tra cui:

  • xlLegendPositionBottom: posiziona la legenda nella parte inferiore del grafico.
  • xlLegendPositionCorner: posiziona la legenda nell'angolo del grafico.
  • xlLegendPositionCustom: colloca la legenda in posizioni personalizzate sul grafico.

Apps Script ha un codice equivalente che supporta solo alcuni di questi valori. I seguenti valori non sono supportati:

  • xlLegendPositionCorner
  • xlLegendPositionCustom

Per segnalare i valori non supportati delle API parzialmente supportate nel codice convertito, viene aggiunta una condizione di convalida al file library.gs che verifica la presenza di questi valori. Ad esempio:

if (position == xlLegendPositionCorner ||
     position == xlLegendPositionCustom) {
   position = _handle_legend_position_error(position);
}

Se la condizione di convalida trova uno dei valori non supportati, nel file unimplemented_constructs.gs viene creata una funzione per la gestione degli errori, _handle_<API_name>_error.

La funzione genera un errore utente e non sostituisce il valore con un valore supportato. Ad esempio:

/**
* Throw error message for unsupported legend position.
* The VBA API Legend.Position which can take values xlLegendPositionTop,
* xlLegendPositionLeft, xlLegendPositionBottom, xlLegendPositionRight,
* xlLegendPositionCorner, xlLegendPositionCustom. It is partially supported in
* Apps Scripts that supports only a subset of the values (does not support
* xlLegendPositionCorner and xlLegendPositionCustom).
* @param {string} position
*/
function _handle_legend_position_error(position) {
// Please comment the throw statement and return a supported position value
// instead.
// Values that are supported here are xlLegendPositionTop,
// xlLegendPositionLeft, xlLegendPositionBottom, xlLegendPositionRight.
throw new Error(
   'Google Sheets does not support legend position: ' + position);
}

Correggi gli errori dell'API parzialmente supportati

Definisci la funzione _handle_<API_name>_error per sostituire i valori non supportati con una soluzione alternativa accettabile per le tue esigenze.

  1. Apri il codice Apps Script convertito nel punto in cui si trova l'errore. Consulta la sezione Trovare errori.
  2. Leggi il commento sopra la funzione per capire quali valori sono supportati e quali no.
  3. Per i valori non supportati, determina quali valori supportati possono fungere da sostituzione appropriata.
  4. Aggiorna la funzione _handle_<API_name>_error in modo che restituisca un valore supportato.
  5. Se non riesci a trovare un modo per sostituire il valore non supportato, non puoi convertire questa macro.

Esempio di errore dell'API parzialmente supportato

Il seguente esempio si espande sull'API VBA legend_position menzionata sopra. Consulta la sezione API parzialmente supportata.

Di seguito è riportato un esempio di codice VBA originale che utilizza un valore non supportato, xlLegendPositionCustom.

Charts(1).Legend.Position = xlLegendPositionCustom

Macro Converter aggiunge la funzione seguente al file unimplemented_constructs.gs:

/**
* Throw error message for unsupported legend position.
* The VBA API Legend.Position which can take values xlLegendPositionTop,
* xlLegendPositionLeft, xlLegendPositionBottom, xlLegendPositionRight,
* xlLegendPositionCorner, xlLegendPositionCustom. It is partially supported in
* Apps Scripts that supports only a subset of the values (does not support
* xlLegendPositionCorner and xlLegendPositionCustom).
* @param {string} position
*/
function _handle_legend_position_error(position) {
// Please comment the throw statement and return a supported position value
// instead.
// Values that are supported here are xlLegendPositionTop,
// xlLegendPositionLeft, xlLegendPositionBottom, xlLegendPositionRight.
throw new Error(
   'Google Sheets does not support legend position: ' + position);
}

Lavoro manuale necessario

È necessario un lavoro manuale significa che l'API VBA può essere convertita in Apps Script, ma ha bisogno di una soluzione alternativa.

Nel report sulla compatibilità generato prima della conversione, questo tipo di API è etichettato come Supportato con soluzioni alternative.

Se non correggi questo tipo di API nel tuo codice VBA prima di convertire il file, ecco come apparirà nel progetto Apps Script:

/**
* Could not convert  API. Please add relevant code in the following
* function to implement it.
* This API has been used at the following locations in the VBA script.
*      : 
*
* You can use the following Apps Script APIs to convert it.
* Apps Script APIs : 
* Apps Script documentation links : 
*
* @param param1 {}
* @param param2 {}
* ...
* @return {}
*/
function _api_(param1, param2, ....) {
 ThrowException("API  not supported yet.");
}

Correggere gli errori relativi al lavoro manuale necessario

Implementa una soluzione alternativa per consentire all'API di funzionare come previsto. 1. Apri il codice Apps Script convertito nel punto in cui si trova l'errore. Consulta la sezione Trovare errori. 1. Leggi il commento sopra la funzione per capire quali API possono essere utilizzate per una soluzione alternativa. 1. Se non riesci a trovare una soluzione alternativa, valuta la possibilità di rimuovere l'API dal tuo codice. 1. Se non trovi una soluzione alternativa o rimuovi questa API dal tuo codice e la macro genera un errore, non puoi convertirla.

Esempi di errori relativi al lavoro manuale necessario

Di seguito sono riportati alcuni esempi di API che generano errori relativi al lavoro manuale necessario e come correggerli:

Esempio 1: Autocorrect.Addreplacement

Nell'esempio seguente, l'API VBA Autocorrect.Addreplacement può essere convertita, ma ha bisogno di una soluzione alternativa. Il convertitore macro suggerisce come implementare la funzione nei commenti del codice.

/**
* Could not convert autocorrect.addreplacement API. Please add relevant code in
* the following function to implement it.
* This API has been used at the following locations in the VBA script.
*     sheet1 : line 3
* You can use the following Apps Script APIs to convert it.
* Apps Script APIs : FindReplaceRequest , onEdit
* Apps Script documentation links :
* https://developers.google.com/apps-script/reference/script/spreadsheet-trigger-builder#onedit
* https://developers.google.com/sheets/api/eap/reference/rest/v4/spreadsheets/request?hl=en#findreplacerequest

* Comments : AutoCorrect.AddReplacement was not converted, but there is an
* equivalent option you can implement manually. Use onEdit and FindReplaceRequest
* APIs instead, see https://developers.google.com/apps-script/reference/script/spreadsheet-trigger-builder#onedit
* and https://developers.google.com/sheets/api/eap/reference/rest/v4/spreadsheets/request?hl=en#findreplacerequest.
* For more information on API manual implementation, see
* https://developers.google.com/apps-script/guides/macro-converter/fix-conversion-errors.

* @param {Object} CallingObject represents the parent object using which the API
* has been called.
* @param {string} What
* @param {string} Replacement
* @return {string}
*/

function _api_autocorrect_addreplacement(CallingObject, What, Replacement) {
  ThrowException('API autocorrect.addreplacement not supported yet.');

}

Di seguito è riportata l'implementazione dell'API Autocorrect.Addreplacement:

var AUTO_CORRECTIONS = "AUTO_CORRECTIONS";
// Need to get the autocorrections set in previous sessions and use them.
var savedAutoCorrections = PropertiesService.getDocumentProperties().getProperty(AUTO_CORRECTIONS);
var autoCorrections = savedAutoCorrections ? JSON.parse(savedAutoCorrections) : {};
function onEdit(e) {
autoCorrect(e.range);
}
function autoCorrect(range) {
for (key in autoCorrections) {
// Replace each word that needs to be auto-corrected with their replacements.
range.createTextFinder(key)
.matchCase(true)
.matchEntireCell(false)
.matchFormulaText(false)
.useRegularExpression(false)
.replaceAllWith(autoCorrections[key]);
}
}
/**
* Could not convert autocorrect.addreplacement API. Please add relevant code in
* the following function to implement it.
* This API has been used at the following locations in the VBA script.
* sheet1 : line 3
*
* You can use the following Apps Script APIs to convert it.
* Apps Script APIs : createTextFinder , onEdit
* Apps Script documentation links : https://developers.google.com/apps-script/reference/script/spreadsheet-trigger-builder#onedit ,
createTextFinder
* Comments : AutoCorrect.AddReplacement was not converted, but there is an
* equivalent option you can implement manually. Use onEdit and FindReplaceRequest
* APIs instead, see https://developers.google.com/apps-script/reference/script/spreadsheet-trigger-builder#onedit
* and createTextFinder. For more information on API manual implementation, see
* https://developers.google.com/apps-script/guides/macro-converter/fix-conversion-errors.
*
* @param {Object} CallingObject represents the parent object using which the API has been called.
* @param {string} What
* @param {string} Replacement
*
* @return {string}
*/

function _api_autocorrect_addreplacement(CallingObject, What, Replacement) {
autoCorrections[What] = Replacement;
// Store the updated autoCorrections in the properties so that future executions use the correction.
PropertiesService.getDocumentProperties().setProperty(AUTO_CORRECTIONS, JSON.stringify(autoCorrections));
}

Esempio 2: Workbook.open()

L'API VBA workbook.open() apre un file locale in base a un percorso file.

Supponiamo che workbook.open() nel codice VBA apra due file:

  • File 1: C:\Data\abc.xlsx
  • File 2: C:\Data\xyz.xlsx

Di seguito viene mostrato come Macro Converter sostituisce Workbook.open() con Apps Script ovunque viene utilizzato Workbook.open() per aprire il File 1:

var spreadSheetId =
   _handle_mso_excel_get_google_spreadsheet_id("C:\Data\abc.xlsx");
var spreadSheet = SpreadsheetApp.openById(spreadSheetId);
Il seguente errore viene aggiunto al file unimplemented_constructs.gs nel progetto Apps Script:
/**
* Method to return the spreadsheet id manually.
*
* @param {string} FileName ID of the spreadsheet to be opened.
* @return {string} return the spreadsheet id.
*/
function _handle_mso_excel_get_google_spreadsheet_id(FileName) {
 // Upload the Excel files being opened by the API to Google Drive and convert
 // them to Google Sheets.
 // Determine the spreadsheet ID of the Google Sheets file created.
 // Implement this method to return the corresponding spreadsheet ID when given
 //the original file path as parameter.
 throw new Error('Please return the spreadsheet ID corresponding to filename: ' + FileName);
 return '';
}

Come indicato nei commenti nell'esempio precedente, devi convertire i file di destinazione in file di Fogli Google su Google Drive.

Gli ID del foglio di lavoro Google corrispondenti sono evidenziati in grassetto qui sotto:

  • Il file 1: C:\Data\abc.xlsx diventa https://docs.google.com/spreadsheets/d/abc123Abc123Abc123abc
  • Il file 2: C:\Data\abc.xlsx diventa https://docs.google.com/spreadsheets/d/xyz456Xyz456xYz456xyZ

Quindi, modifica il codice nella funzione Apps Script per aprire i file in base all'ID, come mostrato di seguito:

/**
* Method to return the spreadsheet id manually.
*
* @param {string} FileName ID of the spreadsheet to be opened.
* @return {string} return the spreadsheet id.
*/
function _handle_mso_excel_get_google_spreadsheet_id(FileName) {
 // Upload the Excel files being opened by the API to Google Drive and convert
 //them to Google Sheets.
 // Determine the spreadsheet ID of the Google Sheets file created.
 // Implement this method to return the corresponding spreadsheet ID when given
 //the original file path as parameter
 if (Filename.indexOf("abc.xlsx") >= 0) {
   return "abc123Abc123Abc123abc";
 } else if (Filename.indexOf("xyz.xlsx") >= 0) {
   return "xyz456Xyz456xYz456xyZ";
 }

Errore intenzionale

Al codice convertito vengono aggiunti errori intenzionali per simulare il comportamento di errore del codice VBA originale. Non è necessario modificare questi errori.

Esempio di errore intenzionale

Se tenti di accedere a un elemento oltre i limiti di un array in VBA, il codice genera un'eccezione. In Apps Script, il codice restituisce undefined.

Per evitare risultati imprevisti, Macro Converter aggiunge il codice Apps Script che genera un'eccezione se tenti di accedere a elementi oltre i limiti di un array.

Questo esempio è mostrato nel codice seguente:

Codice VBA originale
Dim arr
arr = Array("apple", "orange")
MsgBox arr(5)
Will throw the following error:
Subscript out of range
Codice Apps Script convertito (prima dell'aggiunta di un errore di eccezione)
var arr;
arr = ["apple", "orange"];
Browser.msgBox(arr[5]);
Will return this value and not throw an error:
undefined
Codice Apps Script aggiunto per generare l'errore di eccezione
/**
* Extend the regular JS array to support VB style indexing with a get method.
* @returns{*} value at the index
*/
Array.prototype.get = function() {
 var curr_res = this;
 for (var i = 0; i < arguments.length; i++) {
   if (!Array.isArray(curr_res) || curr_res.length < arguments[i]) {
     throw new Error(‘Converted VBA Error (Intentional Error): Subscript out of range’);
   }
   curr_res = curr_res[arguments[i]];
 }
 return curr_res;
};
var arr;
arr  = ["apple", "orange"];
Browser.msgBox(arr.get(5));