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

Macro Converter 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 Script'te 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.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 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. Macro Converter, benzer 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.

Örneği kod olarak 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, örneğin bir API'nin birden fazla dönüş türü olması veya nesnenin kendisinin bir varyant olarak bildirilmesi gibi çeşitli nedenlerden kaynaklanabilir.

Makro Dönüştürücü, bu dosyaya __handle_resolve_<api>() adlı yeni bir işlev ekler. Bu işlev, söz konusu API'nin yerini alır ve nesne türünü belirlemeye yardımcı olur.

Bazı durumlarda, nesne türünü manuel olarak bildirmek için __handle_resolve_<api>() işlevini güncellemeniz gerekebilir. Desteklenmeyen nesne türü başlıklı makaleyi inceleyin.

Örnek: name()

VBA'daki birçok nesne türü, name() API'sini tanımlar. Genellikle Apps Komut Dosyası 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 API'si getName() dışında bir adla çağrılıyor.
  • Nesnenin adını almak için Apps Script API'si yok.
  • Eşdeğer bir Apps Komut Dosyası nesnesi yoktur.

Nesne türü belirlenmediğinde Macro Converter, variant_resolutions.gs dosyasında __handle_resolve_name adlı yeni bir işlev oluşturur.

Örneği kod olarak aşağıda bulabilirsiniz:

Orijinal VBA kodu

a = Selection.name

Bu durumda, API name() geçerli seçimde çağrılır. Seçim bir sayfa 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 aşağıdaki __handle_resolve_name() işlevi variant_resolution.gs dosyasına 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;
}

Hata 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ındaysanız 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ının 2. satırındaki 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

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 Komut Dosyası'na dönüştüremediği ve API için bilinen bir geçici çözümün olmadığı bir 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 kodunuzdaki bu tür API'leri 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("API  not supported yet.");
}

Uygulanmamış API hatalarını düzeltme

Uygulanmamış 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ülen Apps Komut Dosyası kodunu hatanın bulunduğu konumda açın. Hataları bulma bölümüne bakın.
  2. İşlevin üst kısmında, eklenen yorumu okuyun. Bazı durumlarda yorum, API'nin Apps Script'te nasıl uygulanacağını önerir.
  3. API'yi Apps Komut Dosyası'nda uygulamanın bir yolunu bulamıyorsanız kodu kaldırmayı düşünebilirsiniz.
  4. 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

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

  • Apps Script'te eşdeğer bir API yok: Apps Script'te bulunmayan bir API olan Chart.Protect iç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 grafik koruma yöntemi 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.');
}
Grafiği koruyamasanız da verilerin değiştirilememesi için grafiğin veri aralığını koruyabilirsiniz.

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 örnek, yukarıdaki VBA name() API örneğini genişletir. variant_resolution.gs sayfasına göz atın.

Bu örnekte şunları öğreneceksiniz:

  1. name() API'sinin variant_resolution.gs dosyasında yeni bir işleve nasıl dönüştürüldüğü.
  2. Dönüştürülen kodda yeni işlevin 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, üzerinde çağrı yapılan nesne türünü tam olarak belirleyemediğinden Makro Dönüştürücü, aşağıda gösterilen name() __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()` işlevi, değişken olan bir nesnede çağrıldığından dönüştürülen kod, dönüştürme sırasında nesne türünü bilmiyor. 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, PrintName() işlevini nesne türünde çağırdığını varsayalım CommandBar. VBA kodu aşağıda gösterilmiştir:

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üm CommandBar nesnelerinin listesini döndürür.
  • CommandBars.item(): VBA'da bu, belirli bir CommandBar nesnesini döndürür.
Bu nesne türü Apps Komut Dosyası'nda desteklenmediği için dönüştürülen kod, tanımlamanız gereken "unimplemented_constructs.gs" dosyasında aşağıdaki işlevleri oluşturur.
  • _api_application_commandbars()
  • _api_commandbars_item()
İşlevler, dönüştürülen kodda 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ı 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 variant_resolution.gs dosyasındaki __handle_resolve_name işlevini değiştirin. İşleve aşağıdaki gibi 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 bir kod dili öğesidir. Örneğin, döngüler, etiketler, etkinlikler ve goto'lar. Tüm VBA yapılarını içeren listeyi 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ının bulunduğ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ın desteklenmeyen dil yapısına dayanmaması için kodunuzu güncelleyin.
  2. Dönüştürülen Apps Komut Dosyası kodunu hatanın bulunduğu konumda açın. Hataları bulma başlıklı makaleyi inceleyin.
  3. Kodu, mantığına göre desteklenmeyen dil yapısını gerektirmeyecek şekilde güncelleyin.
  4. Kodunuzu desteklenmeyen dil yapısı olmadan 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ştirebilirsiniz. Aşağıda, GoTo ifadeleri yerine döngü kullanmayla ilgili 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 ifadesini For Loop 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ı ise desteklenmez.

Örneğin, VBA API legend_position, Excel grafiğinde 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 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:

  • xlLegendPositionCorner
  • xlLegendPositionCustom

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.

  1. Dönüştürülen 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, hangilerinin desteklenmediğini anlamak için işlevin üzerindeki yorumu okuyun.
  3. Desteklenmeyen değerler için hangi desteklenen değerlerin uygun bir alternatif olabileceğini belirleyin.
  4. _handle_<API_name>_error işlevini, desteklenen bir değer döndürecek şekilde güncelleyin.
  5. 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, yukarıda bahsedilen VBA API'si legend_position daha ayrıntılı olarak açıklanmaktadır. Kısmen desteklenen API başlıklı makaleyi inceleyin.

Aşağıda, desteklenmeyen bir değerin kullanıldığı orijinal VBA kodu örneği verilmiştir: xlLegendPositionCustom.

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 kodunuzdaki bu tür API'leri düzeltmezseniz Apps Komut Dosyası projesinde şu ş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ığı ş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 konumda 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 hataları veren API'ler ve bu hataların nasıl düzeltileceği ile ilgili ö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.');

}

Autocorrect.Addreplacement API'nin 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 dosya 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() yerine Apps Komut Dosyası'nı nasıl kullandığı gösterilmektedir. Workbook.open(), Dosya 1'i açmak için kullanılır:

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 harflerle belirtilmiş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, dosyaları kimliğe göre açmak için Apps Komut Dosyası işlevindeki kodu 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";
 }

Kasıtlı hata

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

Kasıtlı hata örneği

VBA'da bir dizinin sınırları 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ı dışındaki öğelere erişmeye çalıştığınızda istisna oluşturan Apps Komut Dosyası 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ını 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));