1

Before some code runs, I want to check it is the correct sheet.

I can use the sheet name, but my concern is that if someone changes the sheet name, the code won't run. The sheet index also seems to change if the sheet is moved.

Therefore I want to use something that doesn't change.

I believe the sheet number and sheet ID never change.

So I was hoping to use one of them, but I can't see a way of doing that.

What I want in non-coding language is:

If active sheet number = 4 then run the code or If active sheet ID = 0123456789 then run the code.


Thanks to JPV's link, I have an answer and learned a few things.

  1. You can't use the sheet number to check if the correct sheet is active.
  2. You can use the getSheetId(), but the return you get is not useable.
  3. To make it useable, you need to add getSheetId().toString().
  4. To do the if statement, I needed two equal signs.

if (SpreadsheetApp.getActiveSheet().getSheetId().toString() == 0123456789) {do this when true}

  1. I've been trying to solve this for days, so I should have come here and asked for help earlier.

The main thing I didn't know was the "toString()" part. It always seems so easy and obvious once I know.

Thank you, JPV.

Nigel
  • 19
  • 5
  • 2
    Maybe this helps: https://stackoverflow.com/questions/26682269/get-google-sheet-by-id – JPV Nov 17 '21 at 10:41
  • Use developer meta data. That stay with the sheet even if the name changes. The Sheet Index – Cooper Nov 17 '21 at 15:37
  • @Nigel You can [answer your own question](https://stackoverflow.com/help/self-answer) with the methods you used to solve your problem, just so it doesn't go unanswered and people with similar issues can also be helped. – Rodrigo Biffi Nov 17 '21 at 16:52
  • @RodrigoBiffi Sorry new at all this, I'll add that now - thanks. – Nigel Nov 17 '21 at 17:26
  • @Cooper I've had a quick look over metadata. It adds some useful extras, but above my coding ability currently. Thank you for making me aware of it. – Nigel Nov 17 '21 at 17:30

1 Answers1

1

Thanks to JPV's link, I have an answer and learned a few things.

  1. You can't use the sheet number to check if the correct sheet is active.
  2. You can use the getSheetId(), but the return you get is not useable.
  3. To make it useable, you need to add getSheetId().toString().
  4. To do the if statement, I needed two equal signs.

if (SpreadsheetApp.getActiveSheet().getSheetId().toString() == 0123456789) {do this when true}

  1. I've been trying to solve this for days, so I should have come here and asked for help earlier.

The main thing I didn't know was the "toString()" part. It always seems so easy and obvious once I know.

Thank you, JPV.

Nigel
  • 19
  • 5