Macro Converter Google Workspace eklentisi, dönüşüm sürecinin büyük bir bölümünü otomatikleştirir ancak kodunuzu tamamlamak için bazı API'lerde ve diğer öğelerde ayarlamalar yapmanız gerekebilir.
Projenize eklenen Apps Komut Dosyası dosyalarını (GS dosyaları) anlamak, farklı hata türlerini yorumlamak ve hataları nasıl düzelteceğinizi öğrenmek için bu kılavuzdan yararlanın.
Projenize eklenen Apps Komut Dosyası dosyalarını anlama
Aşağıdaki konularda yardımcı olmak için Apps Komut Dosyası projenize ek GS dosyaları eklenir:
- Apps Komut Dosyası'nda bulunmayan VBA sabitlerini ve değerlerini tanımlayın.
- Dönüştürülmemiş API'leri uygulayın.
- Varyantları çözün.
Apps Komut Dosyası projenize aşağıdaki GS dosyaları eklenir:
Library.gsUnimplemented_constructs.gsVariant_resolutions.gs
Library.gs
Genel olarak, library.gs dosyasında herhangi bir şeyi değiştirmeniz gerekmez.
library.gs dosyası, VBA kodunuzda kullanılan ancak Apps Komut Dosyası'nda bulunmayan işlevleri ve sabitleri tanımlar. Bu sayede yeni Apps Komut Dosyası kodu, VBA kodunuza daha çok benzer. Ayrıca, library.gs dosyasındaki işlevler veya sabitler her kullanıldığında tanımları tekrarlamanız gerekmez.
Unimplemented_constructs.gs
unimplemented_constructs.gs dosyası, Macro Converter tarafından dönüştürülemeyen yapıları veya API'leri ele alır. Kodunuzun amaçlandığı gibi çalışması için bu dosyayı değiştirmeniz gerekebilir.
Örnek: Window.Activate
Aşağıda, Window.Activate adlı desteklenmeyen bir API'ye örnek verilmiştir. Makro Dönüştürücü, benzer bir ada sahip yeni bir Apps Komut Dosyası işlevi oluşturur ve bunu unimplemented_constructs.gs dosyasında tanımlar. VBA işlevi desteklenmediğinden yeni Apps Komut Dosyası işlevi istisna oluşturur.
Yeni işlev, dönüştürülen Apps Komut Dosyası koduna, orijinal API'nin VBA kodunda kullanıldığı her yere eklenir.
Orijinal API'nin davranışını yeniden oluşturmak için bir geçici çözüm bulursanız yalnızca unimplemented_constructs.gs dosyasındaki işlev tanımını güncellemeniz gerekir. İşlev orada tanımlandıktan sonra, Apps Komut Dosyası projenizde işlevin göründüğü her yerde geçerli olur.
Kod örneğini aşağıda bulabilirsiniz:
Orijinal VBA kodu
Window.activate()
Dönüştürülmüş Apps Komut Dosyası kodu, satır içi olarak eklenir
_api_window_activate();
unimplemented_constructs.gs dosyasına işlev tanımı eklendi
/** * 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
Bir nesnenin türü belirlenemezse variant_resolutions.gs dosyası Apps Komut Dosyası projenize eklenir. Bu durum, bir API'nin birden fazla dönüş türüne sahip olması veya nesnenin kendisinin bir varyant olarak bildirilmesi gibi çeşitli nedenlerle ortaya çıkabilir.
Makro Dönüştürücü, bu dosyaya söz konusu API'nin yerini alan ve nesne türünü belirlemeye yardımcı olan __handle_resolve_<api> adlı yeni bir işlev ekler.
Bazı durumlarda, nesne türünü manuel olarak tanımlamak için __handle_resolve_<api> işlevini güncellemeniz gerekebilir. Desteklenmeyen nesne türü başlıklı makaleye bakın.
Örnek: name yöntemi
VBA'daki birçok nesne türü, name yöntemini tanımlar. Genellikle Apps Komut Dosyası'ndaki karşılığı getName olsa da bu durum her nesne türü için geçerli değildir. Birden fazla alternatif durum oluşabilir:
- Nesnenin eşdeğer yöntemi,
getName'dan farklı bir adla çağrılıyor. - Nesnenin adını almak için Apps Komut Dosyası API'si yok.
- Apps Komut Dosyası'nda eşdeğer bir nesne yoktur.
Nesne türü belirlenmediğinde Macro Converter, variant_resolutions.gs dosyasında __handle_resolve_name adlı yeni bir işlev oluşturur.
Kod örneğini aşağıda bulabilirsiniz:
Orijinal VBA kodu
a = Selection.name
Bu durumda, geçerli seçimde name yöntemi çağrılır. Seçim bir E-Tablo nesnesi veya Şekil nesnesi olabilir. Bu bir Sayfa nesnesi ise çeviri getName olur. Ancak bu bir Şekil nesnesi ise Apps Komut Dosyası'nda eşdeğeri yoktur.
Dönüştürülmüş Apps Komut Dosyası kodu, satır içi olarak eklenir
a = __handle_resolve_name({}, getActiveSelection(), {});
Farklı nesne türlerini çözmek için variant_resolution.gs dosyasına aşağıdaki __handle_resolve_name işlevi eklenir. İşlev, nesne türünü kontrol eder, ardından destekleniyorsa getName işlevini kullanır veya getName desteklenmiyorsa hata verir.
variant_resolution.gs dosyasına işlev tanımı eklendi
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; }
Hataları bulma
Dönüştürülen Apps Komut Dosyası kodunda bir hatayla karşılaştığınızda, mesajda hatanın türü ve konumu belirtilir. Hata mesajının biçimi, kullandığınız Apps Komut Dosyası çalışma zamanına bağlıdır.
Varsayılan V8 çalışma zamanında aşağıdaki gibi bir hata görürsünüz:
_api_windows_active (unimplemented_constructs:2:3)
Bu, hatanın unimplemented_constructs.gs dosyasında 2. satır, 3. karakterde olduğu anlamına gelir.
Desteği sonlandırılan Rhino çalışma zamanını kullanıyorsanız aşağıdakine benzer bir hata görürsünüz:
unimplemented_constructs:2 (_api_windows_active)
Bu, hatanın unimplemented_constructs.gs dosyasının 2. satırında olduğu anlamına gelir.
Hata Türleri
Daha önce açıklanan unimplemented_constructs.gs
ve variant_resolution.gs dosyalarında karşılaştığınız hataların çoğunu düzeltin.
Karşılaşabileceğiniz hata türleri şunlardır:
- Uygulanmamış API
- Uygulanmamış dil yapısı
- Kısmen desteklenen API
- Manuel çalışma gerekiyor
- Kasıtlı Hata (Intentional Error)
Uygulanmamış API
Uygulanmayan API, Macro Converter'ın VBA'dan Apps Komut Dosyası'na dönüştüremediği ve API için bilinen bir geçici çözümün olmadığı API'dir.
Uygulanmamış API'ler genellikle unimplemented_constructs.gs dosyasına boş işlevler olarak (bazen boş imzalarla) eklenir. Nesne türü belirlenemezse uygulanmamış API, bunun yerine variant_resolution.gs dosyasına eklenebilir.
Dönüşümden önce oluşturduğunuz uyumluluk raporunda bu API, Daha fazla araştırma gerekiyor olarak etiketlenir.
Dosyanızı dönüştürmeden önce VBA kodunuzda bu tür bir API'yi düzeltmezseniz Apps Komut Dosyası projesinde şu şekilde görünür:
/** * 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." ); }
Uygulanmamış API hatalarını düzeltme
Uygulanmamış API'yi mevcut Apps Komut Dosyası API'leri veya JS kitaplıklarıyla tanımlayın. Bunu yapmak için şu adımları uygulayın:
- Dönüştürülen Apps Komut Dosyası kodunu hatanın bulunduğu konumda açın. Hataları bulma bölümüne bakın.
- İşlevin üst kısmında, eklenen yorumu okuyun. Bazı durumlarda yorumda, API'nin Apps Komut Dosyası'nda nasıl uygulanacağı önerilir.
- API'yi Apps Komut Dosyası'nda uygulamanın bir yolunu bulamıyorsanız API'yi kodunuzdan kaldırmayı düşünebilirsiniz.
- Bir geçici çözüm bulamıyorsanız veya bu API'yi kodunuzdan kaldıramıyorsanız ve makronuz bu hatayı veriyorsa bu makroyu dönüştüremezsiniz.
Uygulanmamış API hataları örnekleri
Uygulanmayan API senaryoları ve bunların nasıl düzeltileceğine dair örnekleri aşağıda bulabilirsiniz:
- Apps Komut Dosyası'nda eşdeğeri yok:
Apps Komut Dosyası'nda bulunmayan bir API olan
Chart.Protectiçin dolaylı bir geçici çözüm gösterir. - Bilinmeyen bir nesne türü: Değişken olan bir nesne türünün nasıl işleneceğini ve Apps Komut Dosyası'nda yeniden oluşturulabilen desteklenmeyen bir nesne türünün nasıl uygulanacağını gösterir.
1. örnek: Eşdeğer Apps Komut Dosyası veya bilinmeyen API yok
Bu örnekte, Google E-Tablolar'da bir grafiği korumanın yolu olmadığından Chart.Protect otomatik olarak dönüştürülmedi.
/** * 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.'); }
Aşağıda, aralığı korumaya yönelik örnek bir uygulama gösterilmektedir:
/** * 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(); } }
2. örnek: Desteklenmeyen nesne türü
Nesne türü bilinmediğinde, uygulanmayan API hatası variant_resolution.gs dosyasına eklenir. Aşağıdaki örnekte VBA name
yöntemi örneği genişletilmiştir. variant_resolution.gs sayfasına göz atın.
Bu örnekte öğrenecekleriniz:
nameyöntemininvariant_resolution.gsdosyasında yeni bir işleve nasıl dönüştürüldüğü.- Dönüştürülen kodda yeni işlevin nasıl çağrıldığı.
- Apps Komut Dosyası'nda desteklenmeyen bir nesne türü olan
CommandBariçin geçici çözüm oluşturma
1. Dönüştürülen kod, üzerinde çağrılan nesne türünü tam olarak belirleyemediğinden name
makro dönüştürücü, __handle_resolve_name adlı yeni bir işlev oluşturur:
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. VBA kodunun, PrintName() API'sini çağıran bir PrintName() işlevi tanımladığını varsayalım:name
‘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. VBA kodunuzun, PrintName() işlevini nesne türünde çağırdığını varsayalım
CommandBar:
PrintName Application.CommandBars.item("Standard")CommandBar, Apps Komut Dosyası'nda desteklenmediğinden yukarıdaki VBA kodunda kullanılan iki yöntem de desteklenmez.
Application.CommandBars(): VBA'da bu, tümCommandBarnesnelerinin listesini döndürür.CommandBars.item(): VBA'da bu, belirli birCommandBarnesnesini döndürür.
_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.'); }
Yeni işlevlerin çalışması için aşağıdaki adımları uygulayın:
3.1 VBA'daki işlevlere benzer şekilde CommandBars işlevlerini ve yeni bir CommandBars koleksiyonunu oluşturan yeni bir nesne türü tanımlayın.
3.2 Yeni nesne türü için bir getName yöntemi ekleyin.
3.1 ve 3.2 adımları aşağıdaki kodda gösterilmektedir. Menü nesneleri, CommandBars davranışını taklit eden yeni bir nesne türü olarak oluşturulur.
// 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 Yeni nesne türünü işlemek için __handle_resolve_name işlevini variant_resolution.gs
dosyasında değiştirin. İşleve bir bölüm ekleyin:
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 unimplemented_constructs.gs dosyasında oluşturulan iki işlevi tanımlayın (_api_application_commandbars, _api_commandbars_item). Bu adım, işlevin orijinal çağrılarının çalışmasını sağlar.
//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); }
Uygulanmamış dil yapıları
Yapı, yürütme akışını veya veri görüntülemeyi kontrol eden kod dilinin bir öğesidir. Örneğin, döngüler, etiketler, etkinlikler ve goto'lar. Tüm VBA yapılarını içeren bir liste için Statements (VBA) başlıklı makaleye bakın.
Makro dönüştürücünün dönüştüremediği yapılar, uygulanmamış dil yapıları olarak kabul edilir.
Makro Dönüştürücü, uygulanmamış bir dil yapısının bulunduğunu belirlediğinde TODO yorumu ekler.
Aşağıdaki VBA yapıları desteklenmez:
- AddressOf
- Tanımlama
- DefType
- GoSub
- GoTo
- Uygulamalar
- Lset
- Aç
- RaiseEvent
- Ad
- Devam ettir
- Rset
- TypeOf
- Sınıf
- Sınıf Modülleri
Uygulanmamış dil yapısı hatalarını düzeltme
- Kodunuzu, mantığınızın desteklenmeyen dil yapısına bağlı olmayacak şekilde güncelleyin.
- Dönüştürülen Apps Komut Dosyası kodunu hatanın bulunduğu konumda açın. Hataları bulma başlıklı makaleyi inceleyin.
- Kodu, mantığına göre desteklenmeyen dil yapısını gerektirmeyecek şekilde güncelleyin.
- Kodunuzu desteklenmeyen dil yapısını kullanmadan yeniden yazmanın bir yolunu bulamıyorsanız bu makroyu dönüştüremezsiniz.
Uygulanmamış dil yapısı hataları örnekleri
En yaygın olarak uygulanmayan dil yapıları arasında GoTo ifadesi yer alır.
Bazı VBA GoTo ifadelerini döngülerle değiştirin. Aşağıdaki örneklerde GoTo ifadeleri yerine döngüler kullanılmaktadır.
1. örnek: GoTo yerine While Loop koyun
Orijinal VBA kodu
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 Subfunction 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); }
2. örnek: GoTo ifadesini For Loop ile değiştirme
Orijinal VBA koduSub 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 Subfunction 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); }
Kısmen desteklenen API
Kısmen desteklenen API'ler için bazı giriş parametreleri Apps Komut Dosyası'nda desteklenir, bazıları ise desteklenmez.
Örneğin, VBA API legend_position, Excel grafiğindeki göstergeyi tanımlamak için kullanılır. Aşağıdakiler dahil olmak üzere çeşitli giriş değeri türlerini destekler:
xlLegendPositionBottom: Açıklamayı grafiğin en altına yerleştirir.xlLegendPositionCorner: Açıklamayı grafiğin köşesine yerleştirir.xlLegendPositionCustom: Açıklamayı grafikteki özel konumlara yerleştirir.
Apps Komut Dosyası'nda, bu değerlerin yalnızca bazılarını destekleyen eşdeğer bir kod vardır. Aşağıdaki değerler desteklenmez:
xlLegendPositionCornerxlLegendPositionCustom
Dönüştürülen kodunuzda kısmen desteklenen API'lerin desteklenmeyen değerlerini işaretlemek için library.gs dosyasına bu değerleri kontrol eden bir doğrulama koşulu eklenir. Örneğin:
if (position == xlLegendPositionCorner ||
position == xlLegendPositionCustom) {
position = _handle_legend_position_error(position);
}
Doğrulama koşulu, desteklenmeyen değerlerden birini bulursa unimplemented_constructs.gs dosyasında bir hata işleyici işlevi (_handle_<API_name>_error) oluşturulur.
İşlev, kullanıcı hatası verir ve değeri desteklenen bir değerle değiştirmez. Örneğin:
/** * 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); }
Kısmen desteklenen API hatalarını düzeltme
Desteklenmeyen değerleri ihtiyaçlarınıza uygun kabul edilebilir bir geçici çözümle değiştirmek için _handle_<API_name>_error işlevini tanımlayın.
- Dönüştürülen Apps Komut Dosyası kodunu hatanın bulunduğu konumda açın. Hataları bulma bölümüne bakın.
- Hangi değerlerin desteklendiğini ve hangilerinin desteklenmediğini anlamak için fonksiyonun üzerindeki yorumu okuyun.
- Desteklenmeyen değerler için hangi desteklenen değerlerin uygun bir alternatif olabileceğini belirleyin.
_handle_<API_name>_errorişlevini, desteklenen bir değer döndürecek şekilde güncelleyin.- Desteklenmeyen değeri değiştirecek bir yol bulamıyorsanız bu makroyu dönüştüremezsiniz.
Kısmen desteklenen API hatası örneği
Aşağıdaki örnekte, daha önce bahsedilen VBA API legend_position daha ayrıntılı olarak açıklanmaktadır.
Kısmen desteklenen API başlıklı makaleyi inceleyin.
Aşağıdaki örnekte, desteklenmeyen bir değer olan xlLegendPositionCustom'yı kullanan orijinal VBA kodu gösterilmektedir.
Charts(1).Legend.Position = xlLegendPositionCustom
Makro dönüştürücü, unimplemented_constructs.gs dosyasına aşağıdaki işlevi ekler:
/** * 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); }
Manuel çalışma gerekiyor
Manuel çalışma gerekiyor, VBA API'sinin Apps Komut Dosyası'na dönüştürülebileceği ancak geçici bir çözüm gerektirdiği anlamına gelir.
Dönüşümden önce oluşturduğunuz uyumluluk raporunda bu tür API'ler Geçici çözümlerle desteklenir olarak etiketlenir.
Dosyanızı dönüştürmeden önce VBA kodunuzda bu tür bir API'yi düzeltmezseniz Apps Komut Dosyası projesinde şu şekilde görünür:
/** * 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." ); }
Manuel çalışma gerektiren hataları düzeltme
API'nin amaçlandığı şekilde çalışması için API'de geçici bir çözüm uygulayın. 1. Dönüştürülen Apps Komut Dosyası kodunu hatanın bulunduğu yerde açın. Hataları bulma bölümüne bakın. 1. Hangi API'lerin geçici çözüm için kullanılabileceğini anlamak üzere işlevin üzerindeki yorumu okuyun. 1. Uygun bir geçici çözüm bulamıyorsanız API'yi kodunuzdan kaldırmayı düşünebilirsiniz. 1. Bir geçici çözüm bulamıyorsanız veya bu API'yi kodunuzdan kaldıramıyorsanız ve makronuz hata veriyorsa bu makroyu dönüştüremezsiniz.
Manuel çalışma gerektiren hatalara örnekler
Aşağıda, "Manuel çalışma gerekiyor" hatası veren API'ler ve bu hataların nasıl düzeltileceğine dair örnekler verilmiştir:
1. örnek: Autocorrect.Addreplacement
Aşağıdaki örnekte, VBA API'si Autocorrect.Addreplacement dönüştürülebilir ancak geçici bir çözüm gerektirir. Makro dönüştürücü, işlevin kod yorumlarında nasıl uygulanacağını önerir.
/** * 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.'); }
Aşağıdaki örnekte Autocorrect.Addreplacement API'sinin uygulanması gösterilmektedir:
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)); }
2. örnek: Workbook.open yöntemi
VBA API'si workbook.open bir yola göre yerel bir dosya açar.
VBA kodunda workbook.open tarafından açılan iki dosya olduğunu varsayalım:
- Dosya 1:
C:\Data\abc.xlsx - Dosya 2:
C:\Data\xyz.xlsx
Aşağıdaki kodda, Macro Converter'ın Workbook.open yerine Apps Komut Dosyası'nı nasıl kullandığı gösterilmektedir. Workbook.open, Dosya 1'i açmak için her yerde kullanılır:
var spreadSheetId = _handle_mso_excel_get_google_spreadsheet_id("C:\Data\abc.xlsx"); var spreadSheet = SpreadsheetApp.openById(spreadSheetId);
unimplemented_constructs.gs dosyasına eklenir:
/** * 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 '' ; }
Önceki örnekteki yorumlarda belirtildiği gibi, hedef dosyaları Drive'da E-Tablolar dosyalarına dönüştürmeniz gerekir.
İlgili Google E-Tablo kimlikleri aşağıdaki listede vurgulanmıştır:
- 1. dosya:
C:\Data\abc.xlsx,https://docs.google.com/spreadsheets/d/abc123Abc123Abc123abcolur. - 2. dosya:
C:\Data\xyz.xlsx,https://docs.google.com/spreadsheets/d/xyz456Xyz456xYz456xyZolur
Ardından, dosyaları kimliğe göre açmak için Apps Komut Dosyası işlevindeki kodu değiştirin:
/** * 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"; }
Kasıtlı hata
Orijinal VBA kodunuzun hata davranışını taklit etmek için dönüştürülen kodunuza amaçlı hatalar eklenir. Bu hataları değiştirmeniz gerekmez.
Kasıtlı hata örneği
VBA'da bir dizinin sınırlarının dışındaki bir öğeye erişmeye çalışırsanız kod bir istisna oluşturur. Apps Komut Dosyası'nda kod, tanımlanmamış olarak döndürülüyor.
Beklenmeyen sonuçları önlemek için Makro Dönüştürücü, bir dizinin sınırlarının dışındaki öğelere erişmeye çalıştığınızda hata veren Apps Komut Dosyası kodu ekler.
Bu örnek, aşağıdaki kodda gösterilmektedir:
Orijinal VBA koduDim arr
arr = Array("apple", "orange")
MsgBox arr(5)
Will throw the following error:
Subscript out of rangevar 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));
İlgili makaleler
- Macro Converter eklentisine genel bakış
- VBA makrolarının uyumlu olup olmadığını belirleme
- VBA makrolarını Apps Komut Dosyası'na dönüştürme
- Sık karşılaşılan sorunları giderme
- Makro dönüştürücü eğitimlerini izleyin
- Uyumlu VBA API'lerinin listesi