Search code examples
javascriptgoogle-sheetsuser-defined-functionsdynamic-arraysvariant-array

Variant Array Custom Function Google Sheets? VBA For Example


The following function below will add "1" to every column across the excel sheet. If I put =vbe(12) in A1, it will put "1" in columns "A1:L1". How can I translate this VBA to JavaScript for Google Sheets?

Function vbe(Num As Long) As Variant
   Dim ary As Variant
   Dim i As Long
   ReDim ary(Num - 1)
   For i = 0 To Num - 1
      ary(i) = 1
   Next i
   vbe = ary
End Function

Example


Solution

  • You can write a custom formula that creates an array of "1"s with the length as a specified parameter, e.g.

    function myFunction(numberColumns) {
      var ones=[];
      ones[0]=[];
      for(var i=0;i<numberColumns;i++){
        ones[0].push(1);
      }
      return ones;
    }
    

    Now, you just need to call the function from a cell, e.g. by typing

    =myFunction(12)

    Useful information can be found in the documentation about Custom Functions in Google Sheets and Google Apps Script.