Dönüştürülen kodunuzdaki hataları düzeltme

Makro Dönüştürücü eklentisi, dönüşüm sürecinin çoğunu 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ılavuzu kullanın.

Projenize eklenen Apps Komut Dosyası dosyalarını anlama

Apps Komut Dosyası projenize aşağıdakiler için yardımcı olacak ek GS dosyaları eklenir:

  • Apps Script'te bulunmayan VBA sabitlerini ve değerlerini tanımlayın.
  • Dönüştürülmemiş API'leri uygulayın.
  • Varyantları çözme

Apps Komut Dosyası projenize aşağıdaki GS dosyaları eklenir:

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

Library.gs

Genel olarak library.gs dosyasında herhangi bir değişiklik yapmanız gerekmez.

library.gs dosyası, VBA kodunuzda kullanılan ve Apps Script'te bulunmayan işlevleri ve sabitleri tanımlar. Bu, yeni Apps Komut Dosyası kodunun VBA kodunuza daha çok benzemesine yardımcı olur. Ayrıca, library.gs dosyasında bulunan 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 adresler. Kodunuzun istenen şekilde çalışması için büyük olasılıkla bu dosyayı değiştirmeniz gerekir.

Örnek: Window.Activate()

Aşağıda, Window.Activate() adlı desteklenmeyen bir API örneği verilmiştir. Macro Converter, benzer ada sahip yeni bir Apps Komut Dosyası işlevi oluşturur ve bu işlevi unimplemented_constructs.gs dosyasında tanımlar. VBA işlevi desteklenmediğinden yeni Apps Komut Dosyası işlevi istisna atar.

Yeni işlev, VBA kodunda orijinal API'nin kullanıldığı her yerde dönüştürülmüş Apps Komut Dosyası koduna eklenir.

Orijinal API'nin davranışını yeniden oluşturmak için bir geçici çözüm bulursanız tek yapmanız gereken unimplemented_constructs.gs dosyasında işlevin tanımını güncellemektir. İşlev burada tanımlandıktan sonra, Apps Komut Dosyası projenizde göründüğü her yerde geçerli olur.

Koddaki örnek:

Orijinal VBA kodu

Window.activate()

Dönüştürülmüş Apps Komut Dosyası kodu, satır içi eklendi

_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, API'nin birden fazla döndürme türüne sahip olması veya nesnenin kendisi bir varyant olarak tanımlanması gibi birden fazla nedenden dolayı ortaya çıkabilir.

Makro Dönüştürücü, 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 beyan etmek için __handle_resolve_<api>() işlevini güncellemeniz gerekebilir. Desteklenmeyen nesne türü bölümüne bakın.

Örnek: name()

VBA'daki birçok nesne türü bir name() API'si tanımlar. Genellikle Apps Script eşdeğeri getName()'tür ancak her nesne türü için geçerli değildir. Birden fazla alternatif durum ortaya çıkabilir:

  • Nesnenin eşdeğer API'si getName()'ten farklı bir şekilde adlandırılır.
  • Nesnenin adını alacak bir Apps Script API'si yok.
  • Eşdeğer bir Apps Komut Dosyası nesnesi yok.

Nesne türü belirlenmediğinde Makro Dönüştürücü, variant_resolutions.gs dosyasında __handle_resolve_name adlı yeni bir işlev oluşturur.

Koddaki örnek:

Orijinal VBA kodu

a = Selection.name

Bu durumda, geçerli seçimde name() API'si çağrılır. Seçim bir E-Tablo nesnesi veya Şekil nesnesi olabilir. Sayfa nesnesi ise çeviri getName() olur ancak Şekil nesnesi ise Apps Komut Dosyası'nda eşdeğeri yoktur.

Dönüştürülmüş Apps Komut Dosyası kodu, satır içi eklendi

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

Aşağıdaki __handle_resolve_name() işlevi, farklı nesne türlerini çözmek için variant_resolution.gs dosyasına eklenir. İşlev, nesne türünü kontrol eder, ardından destekleniyorsa getName()'ü kullanır veya desteklenmiyorsa hata verir.getName()

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ülmüş Apps Script kodunda bir hatayla karşılaşırsanız mesajda hatanın türü ve konumu belirtilir. Hata mesajının biçimi, kullandığınız Apps Script çalışma zamanına bağlıdır.

Varsayılan V8 çalışma zamanındaysanız aşağıdakine benzer bir hata görürsünüz:

_api_windows_active (unimplemented_constructs:2:3)

Bu, hatanın unimplemented_constructs.gs dosyasının 2. satırındaki 3. karakterde olduğu anlamına gelir.

Desteği sonlandırılan Rhino çalışma zamanındaysanı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

Yukarıda açıklanan unimplemented_constructs.gs ve variant_resolution.gs dosyalarında karşılaştığınız hataların çoğunu düzeltebilirsiniz.

Karşılaşabileceğiniz hata türleri şunlardır:

Uygulanmamış API

Uygulanmamış API, Macro Converter'ın VBA'dan Apps Script'e dönüştüremediği ve API için bilinen bir geçici çözümü olmayan bir API'dir.

Uygulanmamış API'ler genellikle unimplemented_constructs.gs dosyasına boş işlevler olarak (bazen boş imzalar da eklenir) 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 inceleme gerekiyor olarak etiketlenmiştir.

Dosyanızı dönüştürmeden önce VBA kodunuzdaki bu API türünü düzeltmezseniz Apps Komut Dosyası projesinde aşağıdaki ş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("API  not supported yet.");
}

Uygulanmamış API hatalarını düzeltme

Uygulamaya geçirilmemiş API'yi mevcut Apps Script API'leri veya JS kitaplıklarıyla tanımlayın. Bunu yapmak için şu adımları uygulayın:

  1. Dönüştürülmüş Apps Komut Dosyası kodunu hatanın bulunduğu konumda açın. Hataları bulma bölümüne bakın.
  2. İşlevin üzerinde, eklenen yorumu okuyun. Bazı durumlarda yorumda, API'nin Apps Script'e nasıl uygulanacağı önerilir.
  3. API'yi Apps Script'e uygulamanın bir yolunu bulamıyorsanız kodunuzdan kaldırabilirsiniz.
  4. Bu sorunun geçici bir çözümünü bulamaz veya bu API'yi kodunuzdan kaldıramazsanız ve makronuz bu hatayı verirse makroyu dönüştüremezsiniz.

Uygulanmamış API hatalarına örnekler

Aşağıda, uygulanmayan API senaryoları ve bunların nasıl düzeltileceğiyle ilgili örnekler verilmiştir:

  • Eşdeğer Apps Script yok: Apps Script'te bulunmayan bir API olan Chart.Protect için dolaylı bir geçici çözüm gösterir.
  • Bilinmeyen nesne türü: Değişken olan bir nesne türünün nasıl kullanılacağını 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 Script yok veya API bilinmiyor

Bu örnekte, Google E-Tablolar'da bir grafiği korumanın bir yolu olmadığı için Chart.Protect otomatik olarak dönüştürülmemiştir.

/**
* 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.');
}
Bir grafiği koruyamasanız da verilerin değiştirilmemesi için grafiğin veri aralığını koruyabilirsiniz.

Aralığın korunmasına ilişkin örnek bir uygulama aşağıda gösterilmiştir:
/**
* 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, yukarıdaki VBA name() API örneği genişletilmiştir. variant_resolution.gs adresine göz atın.

Bu örnekte şunları öğreneceksiniz:

  1. name() API'sinin variant_resolution.gs dosyasında yeni bir işleve dönüştürülmesi.
  2. Yeni işlevin dönüştürülmüş kodda nasıl çağrıldığı.
  3. Apps Komut Dosyası'nda desteklenmeyen bir nesne türü olan CommandBar için geçici çözüm oluşturma.

1. Dönüştürülen kod, name() işlevinin çağrıldığı nesne türünü tam olarak belirleyemediğinden Makro Dönüştürücü, aşağıda gösterilen __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, name() API'sini çağıran bir PrintName() işlevi tanımladığını varsayalım. VBA kodu aşağıda gösterilmiştir:

‘Defining a function that prints the name of the object in parameter
Sub PrintName(obj as Variant)
  Debug.Print obj.Name
End Sub
`name()`, değişken olan bir nesnede çağrıldığı için dönüştürülen kod, dönüştürme sırasındaki nesne türünü bilmez. Dönüştürülen Apps Komut Dosyası kodu, "__handle_resolve_name" işlevini çağırır:
function PrintName(obj) {
  Logger.log(_handle_resolve_name(obj));
}

3. VBA kodunuzun CommandBar nesne türünde PrintName() işlevini çağırdığını varsayalım. VBA kodu aşağıda gösterilmiştir:

PrintName Application.CommandBars.item("Standard")
CommandBar, Apps Komut Dosyası'nda desteklenmez. Bu nedenle, yukarıdaki VBA kodunda kullanılan iki yöntem de desteklenmez.
  • Application.CommandBars(): VBA'da bu işlev, tüm CommandBar nesnelerinin listesini döndürür.
  • CommandBars.item(): VBA'da bu işlev belirli bir CommandBar nesnesi döndürür.
Bu nesne türü Apps Komut Dosyası'nda desteklenmediği için dönüştürülen kod, "unimplemented_constructs.gs" dosyasında tanımlamanız gereken aşağıdaki işlevleri oluşturur.
  • _api_application_commandbars()
  • _api_commandbars_item()
Dönüştürülmüş kodda işlevler aşağıda gösterildiği gibi çağrılır:
PrintName(_api_commandbars_item(_api_application_commandbars(), "Standard")))

Heres 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ını sağlamak için aşağıdaki adımları uygulayın:

3.1 CommandBars işlevlerini oluşturan yeni bir nesne türü ve VBA'dakine benzer yeni bir CommandBars koleksiyonu 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 variant_resolution.gs dosyasında __handle_resolve_name işlevini değiştirin. Aşağıda gösterildiği gibi iş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 (_api_application_commandbars(), _api_commandbars_item()) tanımlayın. Bu adım, işlevin orijinal çağrılarının çalıştığından emin olmanızı 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ı, kod dilinde yürütme akışını veya veri görüntülemeyi kontrol eden bir öğedir. Örneğin, döngüler, etiketler, etkinlikler ve goto'lar. Tüm VBA yapılarının listesini burada bulabilirsiniz.

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ı olduğunu belirlediğinde TODO yorumu ekler.

Aşağıdaki VBA yapıları desteklenmez:

Uygulanmamış dil yapısı hatalarını düzeltme

  1. Mantığınız desteklenmeyen dil yapısını kullanmayacak şekilde kodunuzu güncelleyin.
  2. Dönüştürülmüş Apps Komut Dosyası kodunu hatanın bulunduğu konumda açın. Hataları bulma başlıklı makaleyi inceleyin.
  3. Kodun mantığına göre, desteklenmeyen dil yapısını gerektirmeyecek şekilde güncelleyin.
  4. Desteklenmeyen dil yapısı olmadan kodunuzu yeniden yazmanın bir yolunu bulamıyorsanız bu makroyu dönüştüremezsiniz.

Uygulanmamış dil yapısı hatalarına örnekler

En yaygın uygulanmayan dil yapılarından biri GoTo ifadesidir. Bazı VBA GoTo ifadelerini döngülerle değiştirebilirsiniz. Aşağıda, GoTo ifadeleri yerine döngüler kullanmaya dair iki örnek verilmiştir.

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 Sub
Eşdeğer Apps Komut Dosyası kodu
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);
}

2. Örnek: GoTo'yu For Döngüsü ile Değiştirme

Orijinal VBA kodu
Sub Test()
 a = 0
 For i = 1 to 100
   For j = 1 to 10
     a =a a + 1
     If i + j > 50
       GoTo endLoop
     End If
   Next j
 Next i
 endLoop: MsgBox a
End Sub
Eşdeğer Apps Komut Dosyası kodu
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);
}

Kısmen desteklenen API

Kısmen desteklenen API'ler için bazı giriş parametreleri Apps Script'te desteklenir, bazıları desteklenmez.

Örneğin, VBA API legend_position, Excel grafiğindeki açıklama metnini tanımlamak için kullanılır. Aşağıdakiler dahil olmak üzere birden fazla giriş değeri türünü destekler:

  • xlLegendPositionBottom: Açıklamayı grafiğin alt kısmına yerleştirir.
  • xlLegendPositionCorner: Açıklamayı grafiğin köşesine yerleştirir.
  • xlLegendPositionCustom: Açıklama bölümünü grafikte ö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:

  • xlLegendPositionCorner
  • xlLegendPositionCustom

Dönüştürülmüş 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 _handle_<API_name>_error hata işleyici işlevi 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 bir geçici çözümle değiştirmek için _handle_<API_name>_error işlevini tanımlayın.

  1. Dönüştürülmüş Apps Komut Dosyası kodunu hatanın bulunduğu konumda açın. Hataları bulma bölümüne bakın.
  2. Hangi değerlerin desteklendiğini ve hangilerinin desteklenmediğini öğrenmek için işlevin üzerindeki yorumu okuyun.
  3. Desteklenmeyen değerler için hangi desteklenen değerlerin uygun bir değişim değeri olabileceğini belirleyin.
  4. Bunun yerine, _handle_<API_name>_error işlevini desteklenen bir değer döndürecek şekilde güncelleyin.
  5. Desteklenmeyen değeri değiştirmenin bir yolunu bulamıyorsanız bu makroyu dönüştüremezsiniz.

Kısmen desteklenen API hatası örneği

Aşağıdaki örnekte, yukarıda bahsedilen VBA API'si legend_position ayrıntılı olarak açıklanmıştır. Kısmen desteklenen API başlıklı makaleyi inceleyin.

Aşağıda, desteklenmeyen bir değer (xlLegendPositionCustom) kullanan orijinal VBA kodu örneği verilmiştir.

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 gerekli

Manuel çalışma gerekir, VBA API'sinin Apps Script'e dönüştürülebileceği ancak bunun için bir geçici çözümün gerekli olduğu anlamına gelir.

Dönüşümden önce oluşturduğunuz uyumluluk raporunda bu API türü Çözümlerle desteklenir olarak etiketlenir.

Dosyanızı dönüştürmeden önce VBA kodunuzdaki bu API türünü düzeltmezseniz Apps Komut Dosyası projesinde aşağıdaki şekilde görünür:

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

Manuel çalışma gerektiren hataları düzeltme

API'nin amaçlandığı gibi çalışmasını sağlamak için API için bir geçici çözüm uygulayın. 1. Dönüştürülmüş Apps Komut Dosyası kodunu hatanın bulunduğu konumda açın. Hataları bulma bölümüne bakın. 1. Geçici çözüm için hangi API'lerin kullanılabileceğini anlamak üzere işlevin üzerindeki yorumu okuyun. 1. Uygun bir geçici çözüm bulamıyorsanız API'yi kodunuzdan kaldırabilirsiniz. 1. Bu API'yi kodunuzdan kaldıramıyor veya geçici bir çözüm bulamıyorsanız ve makronuz hata veriyorsa makroyu dönüştüremezsiniz.

Manuel çalışma gerektiren hata örnekleri

Aşağıda, manuel çalışma gerektiren hata veren API'lere ve bunları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üme ihtiyaç vardır. 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.');

}

Autocorrect.Addreplacement API'sinin uygulanması aşağıda gösterilmiştir:

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()

VBA API'si workbook.open(), dosya yoluna göre yerel bir dosyayı açar.

VBA kodunda workbook.open() tarafından açılan iki dosya olduğunu varsayalım:

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

Aşağıda, Macro Converter'ın Workbook.open() dosyasını açmak için Workbook.open()'ün kullanıldığı her yerde Workbook.open()'ü Apps Komut Dosyası ile nasıl değiştirdiği gösterilmektedir:

var spreadSheetId =
   _handle_mso_excel_get_google_spreadsheet_id("C:\Data\abc.xlsx");
var spreadSheet = SpreadsheetApp.openById(spreadSheetId);
Aşağıdaki hata, Apps Komut Dosyası projesindeki 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 '';
}

Yukarıdaki örnekteki yorumlarda belirtildiği gibi, hedef dosyaları Google Drive'da Google E-Tablolar dosyalarına dönüştürmeniz gerekir.

İlgili Google E-Tablo kimlikleri aşağıda kalın olarak verilmiştir:

  • 1. dosya: C:\Data\abc.xlsx, https://docs.google.com/spreadsheets/d/abc123Abc123Abc123abc olur
  • 2. dosya: C:\Data\abc.xlsx, https://docs.google.com/spreadsheets/d/xyz456Xyz456xYz456xyZ olur

Ardından, Apps Komut Dosyası işlevindeki kodu, dosyaları kimliğe göre açacak şekilde aşağıdaki gibi 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";
 }

İsteyerek yapılan hata

Orijinal VBA kodunuzun hata davranışını taklit etmek için dönüştürülmüş kodunuza kasıtlı hatalar eklenir. Bu hataları değiştirmeniz gerekmez.

İsteyerek yapılan hata örneği

VBA'da bir dizi sınırlarının dışındaki bir öğeye erişmeye çalışırsanız kod bir istisna oluşturur. Apps Komut Dosyası'nda kod, undefined değerini döndürür.

Beklenmedik sonuçlardan kaçınmak için Makro Dönüştürücü, bir dizinin sınırlarının dışındaki öğelere erişmeye çalıştığınızda istisna atanacak Apps Script kodu ekler.

Bu örnek aşağıdaki kodda gösterilmektedir:

Orijinal VBA kodu
Dim arr
arr = Array("apple", "orange")
MsgBox arr(5)
Will throw the following error:
Subscript out of range
Dönüştürülmüş Apps Komut Dosyası kodu (istisna hatası eklenmeden önce)
var arr;
arr = ["apple", "orange"];
Browser.msgBox(arr[5]);
Will return this value and not throw an error:
undefined
İstisna hatası oluşturmak için eklenen Apps Komut Dosyası kodu
/**
* 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));