Search code examples
excelvbagoogle-sheets-macros

Emulate simple VBA macro to be compatible with Google Sheets


How can I convert this simple VBA to Google Sheets?

Sub SELECT()

Dim Cval As Variant
Cval = Sheet4.Range("A16").Value
Sheet4.Range("D1:T" & Cval).Select

End Sub

I keep getting errors while trying to use this macro in Google Sheets and I cannot find the issue.

The code I'm currently working on in Google Sheets:

function SELECTIE() {
  var spreadsheet = SpreadsheetApp.getActive();
  var Cval = spreadsheet.getRange("A16").Value
  spreadsheet.getRange("D1:T" & Cval).activate();
};

Solution

  • You only have one minor issue.

    In the first statement, you're getting the spreadsheet object, but you need the sheet object. So getSheets()[0] will get you the first worksheet.

    function SELECTIE() {
      var ss = SpreadsheetApp.getActive().getSheets()[0];
      var cVal = ss.getRange('A16').getValue();
      ss.getRange('D1:T' + cVal).activate();
    }