Il componente aggiuntivo Macro Converter automatizza la maggior parte del processo di conversione, ma potresti dover apportare modifiche ad alcune API e ad 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 costanti e valori VBA che non esistono in Apps Script.
- Implementa le API non convertite.
- Risolvi le varianti.
I seguenti file GS vengono aggiunti al tuo progetto Apps Script:
Library.gs
Unimplemented_constructs.gs
Variant_resolutions.gs
Library.gs
In generale, non è necessario modificare nulla nel 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 assomiglia di più al codice VBA. Inoltre, non è necessario ripetere le definizioni ogni volta che vengono utilizzate funzioni o costanti del file library.gs
.
Unimplemented_constructs.gs
Il file unimplemented_constructs.gs
contiene costrutti o API che non è stato possibile
convertire con Macro Converter. Probabilmente devi modificare questo file per far funzionare
il codice come previsto.
Esempio: Window.Activate()
Di seguito è riportato un esempio di API non supportata chiamata Window.Activate()
.
Macro Converter 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, la funzione viene applicata ovunque
nel tuo 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 un oggetto. Ciò può accadere per diversi motivi, ad esempio
un'API con più tipi restituiti o l'oggetto dichiarato come variante
stessa.
Macro Converter aggiunge a questo file una nuova funzione chiamata __handle_resolve_<api>()
che sostituisce l'API in questione e aiuta a determinare il tipo di oggetto.
In alcuni casi, potresti dover aggiornare la funzione __handle_resolve_<api>()
per dichiarare manualmente il tipo di oggetto. Consulta 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 oggetti. Possono verificarsi più casi alternativi:
- L'API equivalente dell'oggetto ha un nome diverso da
getName()
. - L'oggetto non ha un'API Apps Script per ottenere il suo nome.
- Non esiste un oggetto Apps Script equivalente.
Quando il tipo di oggetto non viene determinato, Macro Converter crea una nuova
funzione chiamata __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 sulla selezione corrente. La selezione
può essere un oggetto Foglio o un oggetto Forma. Se si tratta di un oggetto Sheet, la
traduzione è getName()
, ma se si tratta di 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 i problemi relativi a diversi tipi di oggetti. La funzione
controlla il tipo di oggetto, quindi utilizza getName()
se è supportato o 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; }
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 che utilizzi.
Se utilizzi il runtime V8 predefinito, visualizzerai un errore simile al seguente:
_api_windows_active (unimplemented_constructs:2:3)
Ciò significa che l'errore si trova nel file unimplemented_constructs.gs
alla riga
2, carattere 3.
Se utilizzi il runtime Rhino ritirato, visualizzerai un errore simile al seguente:
unimplemented_constructs:2 (_api_windows_active)
Ciò significa che l'errore si trova nel file unimplemented_constructs.gs
alla riga 2.
Tipi di errore
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
- Costrutto di linguaggio non implementato
- API parzialmente supportata
- È necessario un intervento manuale
- Errore intenzionale
API non implementata
Un'API non implementata è un'API che Macro Converter non può convertire da VBA ad Apps Script e per la quale non esiste una soluzione alternativa nota.
Le API non implementate vengono in genere aggiunte come funzioni vuote, a volte con firme vuote, al file unimplemented_constructs.gs
. 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 appare 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_<API_name>(param1, param2, ....) { ThrowException("APInot supported yet." ); }
Correggere gli errori relativi all'API non implementata
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 nella posizione dell'errore. Consulta la sezione Trovare 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 codice.
- Se non riesci a trovare una soluzione alternativa o a rimuovere questa API dal codice e la macro genera questo errore, non puoi convertire la macro.
Esempi di errori dell'API non implementati
Ecco alcuni esempi di scenari API non implementati e come risolverli:
- Non esiste un equivalente di Apps Script:
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: nessuna API 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 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 API non implementata viene aggiunto al file
variant_resolution.gs
. L'esempio seguente si basa sull'esempio di API VBA name()
riportato sopra. Vedi variant_resolution.gs
.
In questo esempio imparerai:
- Come l'API
name()
viene convertita 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 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
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, questo restituisce un elenco di tutti gli oggettiCommandBar
.CommandBars.item()
: in VBA, questo 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 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 riportato di seguito. Gli oggetti di menu vengono creati come un
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
il funzionamento delle chiamate originali della funzione.
//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 costrutto è un elemento del linguaggio di programmazione che controlla il flusso di esecuzione o la visualizzazione dei dati. Ad esempio, loop, etichette, eventi e istruzioni goto. Ecco un elenco di tutti i costrutti VBA.
I costrutti che Macro Converter non può convertire sono considerati costrutti di linguaggio non implementati.
Se Macro Converter rileva la presenza di un costrutto di linguaggio non implementato, inserisce un commento TODO
.
I seguenti costrutti VBA non sono supportati:
- AddressOf
- Dichiara
- DefType
- GoSub
- GoTo
- Implementa
- Lset
- Apri
- RaiseEvent
- Nome
- Riprendi
- Rset
- TypeOf
- Corso
- Moduli del corso
Correggere gli errori relativi a costrutti di linguaggio non implementati
- Aggiorna il codice in modo che la logica non si basi sul costrutto di linguaggio non supportato.
- Apri il codice Apps Script convertito nella posizione dell'errore. Consulta la sezione Trovare gli errori.
- In base alla logica del codice, aggiornalo in modo da non richiedere il costrutto di linguaggio non supportato.
- Se non riesci a trovare un modo per riscrivere il codice senza il costrutto di linguaggio non supportato, non puoi convertire questa macro.
Esempi di errori di costrutti di linguaggio non implementati
Una delle costruzioni del linguaggio più comuni non implementate è l'istruzione GoTo
.
Puoi sostituire alcune istruzioni VBA GoTo
con cicli. Di seguito sono riportati due esempi di utilizzo di loop anziché 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: sostituzione di 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 e altri no.
Ad esempio, l'API VBA legend_position
viene utilizzata per definire la legenda in un
grafico Excel. Supporta più 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
: posiziona la legenda in posizioni personalizzate sul grafico.
Apps Script ha un codice equivalente che supporta solo alcuni di questi valori. Non sono supportati i seguenti valori:
xlLegendPositionCorner
xlLegendPositionCustom
Per segnalare i valori non supportati delle API supportate parzialmente nel codice convertito,
al file library.gs
viene aggiunta una condizione di convalida che controlla 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, viene creata una funzione di gestione degli errori, _handle_<API_name>_error
, nel file unimplemented_constructs.gs
.
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); }
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 nella posizione dell'errore. Consulta la sezione Trovare 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 sostituzione adeguata.
- Aggiorna la funzione
_handle_<API_name>_error
in modo che restituisca 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 supportata
L'esempio seguente si basa sull'API VBA legend_position
menzionata sopra.
Consulta API supportata parzialmente.
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 seguente funzione 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 un intervento manuale 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 appare 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_<API_name>(param1, param2, ....) { ThrowException("APInot supported yet." ); }
Correggere gli errori che richiedono un intervento manuale
Implementa una soluzione alternativa per l'API in modo che funzioni come previsto. 1. Apri il codice Apps Script convertito nella posizione dell'errore. Consulta la sezione Trovare gli 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 tuo codice. 1. Se non riesci a trovare una soluzione alternativa o a rimuovere questa API dal codice e la macro genera un errore, non puoi convertire questa macro.
Esempi di errori che richiedono un intervento manuale
Ecco alcuni esempi di API che generano errori di intervento manuale necessario e come risolverli:
Implement a workaround for Autocorrect.Addreplacement
.Implement a workaround for workbook.open()
. Questo esempio mostra come aprire i file in Google Drive con Apps Script.
Esempio 1: Autocorrect.Addreplacement
Nell'esempio seguente, l'API VBA Autocorrect.Addreplacement
può essere
convertita, ma richiede una soluzione alternativa. Macro Converter 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.'); }
L'implementazione dell'API Autocorrect.Addreplacement
è mostrata di seguito:
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 mostrato come Macro Converter sostituisce Workbook.open()
con Apps
Script ovunque Workbook.open()
venga utilizzato 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 dai commenti nell'esempio precedente, devi convertire i file di destinazione in file Fogli Google su Google Drive.
Gli ID foglio Google corrispondenti sono riportati in grassetto di seguito:
- File 1:
C:\Data\abc.xlsx
diventahttps://docs.google.com/spreadsheets/d/abc123Abc123Abc123abc
- File n. 2:
C:\Data\abc.xlsx
diventahttps://docs.google.com/spreadsheets/d/xyz456Xyz456xYz456xyZ
Poi, 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
Errori intenzionali vengono aggiunti al codice convertito per simulare 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, il convertitore di macro aggiunge codice Apps Script che genera un'eccezione se provi ad accedere a elementi al di fuori dei limiti di un array.
Questo esempio è mostrato nel codice riportato di seguito:
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 delle API VBA compatibili