Il componente aggiuntivo Macro Converter automatizza la maggior parte del processo di conversione, ma potresti dover 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 correggere gli errori.
Informazioni sui file Apps Script aggiunti al tuo progetto
Al tuo progetto Apps Script vengono aggiunti altri file GS per aiutarti a:
- Definire le costanti e i valori VBA che non esistono in Apps Script.
- Implementare le API che non hanno effettuato conversioni.
- Risolvi le varianti.
Al tuo progetto Apps Script vengono aggiunti i seguenti file GS:
Library.gs
Unimplemented_constructs.gs
Variant_resolutions.gs
Library.gs
In genere, non devi modificare nulla nel file library.gs
.
Il file library.gs
definisce le funzioni e le 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 con Macro Converter. Potresti dover modificare questo 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 in questa posizione, la funzione viene applicata ovunque appaia 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 tuo progetto Apps Script se
non è possibile determinare il tipo di un oggetto. Questo può accadere per diversi motivi, ad esempio un'API che ha più tipi di reso o l'oggetto viene dichiarato come variante a sua volta.
Il convertitore macro 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, potresti dover 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()
. Di solito, l'equivalente di Apps Script
è getName()
, ma non per ogni tipo 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 il tipo di oggetto non viene determinato, il convertitore macro 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 chiamata nella selezione corrente. La selezione
potrebbe essere un oggetto Fogli o un oggetto Forma. Se si tratta di un oggetto Fogli, la traduzione è getName()
, ma se si tratta di un oggetto Forma, non esiste una traduzione 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 oppure genera
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; }
Individuare gli 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 sei nel 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 ti trovi nel runtime di 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 errori
Puoi correggere la maggior parte degli errori che riscontri nei file unimplemented_constructs.gs
e variant_resolution.gs
descritti sopra.
I tipi di errori che potresti riscontrare includono:
- API non implementata
- Struttura linguistica non implementata
- API parzialmente supportata
- È necessario un intervento manuale
- Errore intenzionale
API non implementata
Un'API non implementata è un'API che il convertitore macro non può convertire da VBA in Apps Script e non esiste una soluzione alternativa nota per l'API.
In genere, le API non implementate vengono 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 codice VBA prima di convertire il file, ecco come viene visualizzato 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."); }
Correggere gli errori relativi all'API non implementati
Definisci l'API non implementata con le API Apps Script o le librerie JS esistenti. Per farlo, segui questi passaggi:
- Apri il codice Apps Script convertito nel punto in cui si trova l'errore. Consulta Individuare gli errori.
- Sopra la funzione, leggi il commento aggiunto. In alcuni casi, il commento suggerisce come implementare l'API in Apps Script.
- Se non riesci a trovare un modo per implementare l'API in Apps Script, valuta la possibilità di rimuoverla dal tuo codice.
- Se non riesci a trovare una soluzione alternativa o rimuovi questa API dal codice e la macro genera questo errore, non puoi convertire la macro.
Esempi di errori relativi all'API non implementati
Di seguito sono riportati alcuni esempi di scenari API non implementati e le relative soluzioni:
- Non esiste uno script di Google Apps equivalente:
mostra una soluzione alternativa indiretta per
Chart.Protect
, un'API che non esiste in Apps Script. - Un tipo di oggetto sconosciuto: mostra come gestire un tipo di oggetto che è una variabile e come implementare un tipo di oggetto non supportato che può essere ricreato in Apps Script.
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.'); }
Di seguito è riportata un'implementazione di esempio per la 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 non è noto, l'errore API non implementato viene aggiunto al file variant_resolution.gs
. Il seguente esempio si espande sull'esempio dell'API VBA name()
riportato sopra. Vedi variant_resolution.gs
.
In questo esempio, scoprirai:
- Modalità di conversione dell'API
name()
in una nuova funzione nel filevariant_resolution.gs
. - Come viene chiamata la nuova funzione nel codice convertito.
- Come creare una soluzione alternativa per
CommandBar
, un tipo di oggetto non supportato, in Apps Script.
1. Poiché il codice convertito non è in grado di determinare il tipo esatto di oggetto su cui viene richiamato name()
, Macro Converter crea una nuova funzione denominata
__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 SubPoiché "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 chiama 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 nemmeno i due metodi utilizzati nel codice VBA sopra indicato.
Application.CommandBars()
: in VBA, viene restituito un elenco di tutti gli oggettiCommandBar
.CommandBars.item()
: in VBA, restituisce un oggettoCommandBar
specifico.
_api_application_commandbars()
_api_commandbars_item()
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 utilizzare le nuove funzioni, segui questi passaggi:
3.1 Definisci un nuovo tipo di oggetto che crea 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 imita 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 linguistici non implementati
Un construct è un elemento del linguaggio di 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 della macro non può convertire sono considerati costrutti linguistici non implementati.
Quando il convertitore macro determina l'esistenza di un costrutto linguistico non implementato, inserisce un commento TODO
.
I seguenti costrutti VBA non sono supportati:
- AddressOf
- Dichiara
- DefType
- GoSub
- GoTo
- Implementazioni
- Lset
- Apri
- RaiseEvent
- Nome
- Riprendi
- Rset
- TypeOf
- Corso
- Moduli dei corsi
Correggi gli errori di costruzione del linguaggio non implementato
- Aggiorna il codice in modo che la logica non si basi sul costrutto del linguaggio non supportato.
- Apri il codice Apps Script convertito nel punto in cui si trova l'errore. Vedi Trovare gli errori.
- In base alla logica del codice, aggiornalo in un modo che non richieda il costrutto del linguaggio non supportato.
- 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 costruzione del linguaggio non implementato
Uno dei costrutti linguistici non implementati più comuni è un'istruzione GoTo
.
Puoi sostituire alcune istruzioni VBA GoTo
con i 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
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 originaleSub 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
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, mentre altri no.
Ad esempio, l'API VBA legend_position
viene utilizzata per definire la legenda in un
grafico di Excel. Supporta più tipi di valori di input, tra cui:
xlLegendPositionBottom
: consente di inserire la legenda nella parte inferiore del grafico.xlLegendPositionCorner
: posiziona la legenda nell'angolo del grafico.xlLegendPositionCustom
: posiziona la legenda in posizioni personalizzate nel 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 controlla i
valori in questione. 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 di gestione degli errori, _handle_<API_name>_error
.
La funzione genera un errore dell'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); }
Correggere gli errori relativi alle API parzialmente supportate
Definisci la funzione _handle_<API_name>_error
per sostituire i valori non supportati
con una soluzione alternativa accettabile per le tue esigenze.
- Apri il codice Apps Script convertito nel punto in cui si trova l'errore. Consulta Individuare gli errori.
- Leggi il commento sopra la funzione per capire quali valori sono supportati e quali no.
- Per i valori non supportati, determina quali valori supportati possono fungere da sostituto adeguato.
- Aggiorna la funzione
_handle_<API_name>_error
per restituire un valore supportato. - 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.
Vedi API parzialmente supportata.
Di seguito è riportato un esempio di codice VBA originale che utilizza un valore non supportato, xlLegendPositionCustom
.
Charts(1).Legend.Position = xlLegendPositionCustom
Il convertitore macro aggiunge la funzione riportata di seguito 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); }
È necessario un intervento manuale
È necessario lavorare manualmente significa che l'API VBA può essere convertita in Apps Script, ma è necessaria 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 codice VBA prima di convertire il file, ecco come viene visualizzato nel progetto Apps Script:
/** * Could not convertAPI. 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 alle attività manuali necessarie
Implementa una soluzione alternativa per far funzionare l'API come previsto. 1. Apri il codice Apps Script convertito nel punto in cui si trova l'errore. Consulta 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 adatta, valuta la possibilità di rimuovere l'API dal codice. 1. Se non riesci a trovare una soluzione alternativa o rimuovi questa API dal codice e la macro genera un errore, non puoi convertire la macro.
Esempi di errori relativi al lavoro manuale
Ecco alcuni esempi di API che restituiscono errori relativi alle necessità di lavoro manuale e come correggerli:
Implement a workaround for Autocorrect.Addreplacement
.Implement a workaround for workbook.open()
. Questo esempio mostra come aprire i file su Google Drive con Apps Script.
Esempio 1: Autocorrect.Addreplacement
Nell'esempio seguente, l'API VBA Autocorrect.Addreplacement
può essere
convertita, ma è necessaria una soluzione alternativa. Il convertitore macro suggerisce come implementare
la funzione nei commenti al 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 è illustrata 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 nel codice VBA vengano aperti due file da workbook.open()
:
- File 1:
C:\Data\abc.xlsx
- File 2:
C:\Data\xyz.xlsx
Di seguito viene illustrato in che modo il convertitore macro 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);
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 dei fogli di lavoro Google corrispondenti sono riportati in grassetto di seguito:
- File 1:
C:\Data\abc.xlsx
diventahttps://docs.google.com/spreadsheets/d/abc123Abc123Abc123abc
- File 2:
C:\Data\abc.xlsx
diventahttps://docs.google.com/spreadsheets/d/xyz456Xyz456xYz456xyZ
Quindi, modifica il codice nella funzione Apps Script per aprire i file per 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 imitare il comportamento di errore del codice VBA originale. Non è necessario modificare questi errori.
Esempio di errore intenzionale
Se provi ad 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 codice Apps Script che genera un'eccezione se tenti di accedere a elementi che vanno oltre i limiti di un array.
Questo esempio è mostrato nel codice seguente:
Codice VBA originaleDim arr arr = Array("apple", "orange") MsgBox arr(5) Will throw the following error: Subscript out of range
var arr; arr = ["apple", "orange"]; Browser.msgBox(arr[5]); Will return this value and not throw an error: undefined
/** * 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));
Articoli correlati
- Panoramica del componente aggiuntivo Macro Converter
- Determinare se le macro VBA sono compatibili
- Convertire le macro VBA in Apps Script
- Risolvere i problemi comuni
- Guarda i tutorial di Macro Converter
- Elenco di API VBA compatibili