This is getting to be above my level of knowledge and I was hoping for assistance. The script below works with some limits. This script checks to see if a region tab exists, if it doesn’t, the regional data from the source worksheet is copied to a new tab by the name of that region. Region is column 24 on the source worksheet, the data starts on row 3 and the header is Row 2.
If the region tab already exists I would like for it to be deleted recreated or repopulated with current data instead of being skipped over.
JavaScript
x
32
32
1
function createSheets(){
2
3
const ss = SpreadsheetApp.getActiveSpreadsheet()
4
const sourceWS = ss.getSheetByName("Forecast (SQL) Validation")
5
6
const regions = sourceWS
7
.getRange(3,24,sourceWS.getLastRow()-2,1)
8
.getValues()
9
.map(rng => rng[0])
10
11
const uniqueRegion = [ new Set(regions) ]
12
13
const currentSheetNames = ss.getSheets().map(s => s.getName())
14
15
let ws
16
17
uniqueRegion.forEach(region => {
18
19
if(!currentSheetNames.includes(region)){
20
21
ws = null
22
ws = ss.insertSheet()
23
ws.setName(region)
24
ws.getRange("A2").setFormula(`=FILTER('Forecast (SQL) Validation'!A3:CR,'Forecast (SQL) Validation'!X3:X="${region}")`)
25
sourceWS.getRange("A2:CR2").copyTo(ws.getRange("A1:CR1"))
26
27
}//If regions doesn't exist
28
29
})//forEach loop through the list of region
30
31
} //close createsheets functions
32
Advertisement
Answer
Try it this way
JavaScript
1
19
19
1
function createSheets() {
2
const ss = SpreadsheetApp.getActive()
3
const ssh = ss.getSheetByName("Forecast (SQL) Validation");
4
const regions = ssh.getRange(3, 24, ssh.getLastRow() - 2, 1).getValues().flat();
5
const urA = [new Set(regions)];
6
const shnames = ss.getSheets().map(s => s.getName())
7
let ws;
8
urA.forEach(region => {
9
let idx = shnames.indexOf(region);
10
if (~idx) {
11
ss.deleteSheet(ss.getSheetByName(shnames(idx)));//if it does exist delete it and create a new one
12
}//if it does not exist the just create a new one
13
ws = null;
14
ws = ss.insertSheet(region);
15
ws.getRange("A2").setFormula(`=FILTER('Forecast (SQL) Validation'!A3:CR,'Forecast (SQL) Validation'!X3:X="${region}")`)
16
ssh.getRange("A2:CR2").copyTo(ws.getRange("A1:CR1"))
17
})
18
}
19
Explanation:
Loop through all tabs, and if the tab already exists, delete it via deleteSheet before creating it again, as you are doing with the non-existent ones..