Home > Software design >  Google Sheet Macro - how do I return a column number based on dynamic cell contents?
Google Sheet Macro - how do I return a column number based on dynamic cell contents?

Time:12-08

I have the following code as a starting point. I want to select the entire column where row 3 contains a specific date value (it will be the date of the previous Monday; I have a formula returning this date in cell E1).

function selectDate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  ss.getRange(3,?,1,ss.getMaxColumns()).activate();
}

Basically, the getRange column value would be interpreted as something like: "Find the column number where the value in row 3 is equal to the value in cell E1".

Any ideas would be very helpful, even if it's using a totally different method to achieve the same thing. Thank you so much!

CodePudding user response:

In your situation, how about the following sample script?

Sample script:

function selectDate() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var searchValue = sheet.getRange("E1").getDisplayValue();
  var res = sheet.getRange(3, 1, 1, sheet.getLastColumn()).createTextFinder(searchValue).matchEntireCell(true).findNext();
  if (!res) return;
  var column = res.getColumn();
  sheet.getRange(1, column, sheet.getLastRow()).activate(); // Here, the found column is activated.
  Browser.msgBox("Found column number is "   column); // Here, the found column number is shown in a dialog.
}
  • From your situation, I thought that getRange(3,?,1,ss.getMaxColumns()) in your script might be getRange(3, 1, 1, sheet.getLastColumn()).

  • When this script is run, row 3 is searched using the value of cell "E1". When the value is found, as a sample, the found column is activated and the column number is shown in a dialog. This is a sample. Please modify this for your actual situation.

Note:

  • If no column is selected, it is considered that the value of cell "E1" is not found in row 3. At that time, can you provide the detail of your Spreadsheet? By this, I would like to modify it.

Reference:

  • Related