0
votes

I am attempting to create a script so that when a change is made in one spreadsheet the corresponding sheet with the same name in another spreadsheet receives the same change in the same place, and so I can put one lot of the script in each one and get two linked sheets that affect each other.

this is the code:

var targetID = 'ID of the sheet';
var targetSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();

function onEdit(e){
  var range = e.range;
  var value = e.value;
  var row = range.getRowIndex();
  var column = range.getColumnIndex();
  exportValue(row,column,value)
} 

function exportValue(row,column,value) {
  //(**this is the point where it breaks**)
  var s = SpreadsheetApp.openById(targetID).getSheetByName(targetSheet);
  var target = s.getRange(row, column);
  target.setValue(value);
}

In my version i put in logs in between each line to see where it failed and it got to the line where i have put "this is the point where it breaks" and then didn't return anything after that.

Since attempting this I tried to open up the other file by just pulling out all of the variables but I couldn't get it to work.

the current error messages that it is going with are:

Cannot find function getSheetByName in object Sheet

Cannot find function openById in object Spreadsheet

I have spent so much time on this already and I feel like the answer is really simple but I would really appreciate any advice

Thanks in advance

:)

1
Did you put the target Id here? var targetID = 'ID of the sheet';Cooper
@Cooper thanks for your comment, I put that in just so that people couldn't see my linkOliver Nicholls

1 Answers

0
votes

Linked Spreadsheets with Installable onEdit() triggers

I got this to work by using an installable onEdit(e) Trigger.

function Linked1Edit(e){
  var ss=SpreadsheetApp.openById('The Other Spreadsheets ID');
  var sh=ss.getSheetByName(e.range.getSheet().getName());
  var rg=sh.getRange(e.range.rowStart,e.range.columnStart);
  rg.setValue(e.value);
} 

I called one Linked1Edit(e) and the other Linked2Edit(e) and created an installable onEdit(e) trigger for each one and now they write to each other. Unfortunately, it only works for single valued changes though.

The following script will allow you to make changes to more than one value at a time.

function Linked1Edit(e){
  var ss=SpreadsheetApp.openById('The Other Spreadsheet ID');
  var sh=ss.getSheetByName(e.range.getSheet().getName());
  var rg=sh.getRange(e.range.rowStart,e.range.columnStart,e.range.rowEnd-e.range.rowStart+1,e.range.columnEnd-e.range.columnStart+1);
  var vA=e.range.getValues();
  rg.setValues(vA);
} 

Creating a Trigger

Select Current Project's Triggers

enter image description here

Click Add Trigger:

enter image description here

Create Trigger Dialog:

enter image description here

You can also create a trigger in code. See ScriptApp Class