Shift Cell Range in Google Sheets

馋奶兔 提交于 2020-06-16 17:34:09

问题


I'm trying to take a range of cells and shift them all to the right by one cell. I'd like this to occur once per weekly automatically. I'm aware in the Script editor I can create a trigger for it to schedule weekly, but I'm not sure how to code it.

If someone can help provide a code that allows me to indicate which SHEET and CELL RANGE to shift to the right by one cell, I would appreciate it.

Basically, what I'm trying to accomplish is tracking data for a number of weeks. Each week the sheet will be updated, and I would like the older data to shift right one, basically indicating that the data has gotten a week older.

In addition, I'm only trying to keep data for like 6 weeks, so the data isn't ongoing forever.

A bit of an example: Column A = current week (updated manually). Columns B-F = previous weeks (1-5 weeks ago).

Once a week, the data in columns A-E should be shifted right 1 to preserve the data. After the shift, data is manually updated in Column A to represent the current week. This would then result in showing data for the current week and 5 additional weeks... totaling 6 weeks of data.

I'd be interested if there is a way to just shift columns while excluding the header row, instead of a range, if possible.


回答1:


Could try something like this?

function myFunction() {
   var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];

 // This inserts 1 columns before the first column
 sheet.insertColumnsBefore(1, 1);
  
  // labels the weeks static
      ss.getRange('A1').setFontWeight("bold").setValue("Week1").setBackground("#BBBBBB");
      ss.getRange('B1').setFontWeight("bold").setValue("Week2").setBackground("#BBBBBB");
      ss.getRange('C1').setFontWeight("bold").setValue("Week3").setBackground("#BBBBBB");
      ss.getRange('D1').setFontWeight("bold").setValue("Week4").setBackground("#BBBBBB");
      ss.getRange('E1').setFontWeight("bold").setValue("Week5").setBackground("#BBBBBB");
       ss.getRange('F1').setFontWeight("bold").setValue("Week6").setBackground("#BBBBBB");
}



回答2:


Copy or Cut and Paste

Based upon your last comment I decided to give you another solution. This solution will either copy or cut and paste any range of data from any sheet to a any other range with the same dimensions. The ranges can be on the same page or different pages and the ranges can overlap. Also once you copy a range the document will remember the source and destination ranges so that you can copy or cut and paste them again without having to set up the ranges. If you want to change the range just run the routine and it will give you the choice to clear the range and then you can just run it again and it will remember the new ranges. The copy and cut selection on the menu runs the routine. The Display Properties selection displays you current setup. The clear ranges will just delete everything in DocumentProperties.

But the Copy and Cut selection will give you all of the same info.

function onOpen()
{
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My Tools')
        .addItem('Copy or Cut', 'copyFromToSetupUi')
        .addItem('Display Properties','dispProperties')
        .addItem('Clear Ranges','clearCopyProperties')
        .addToUi();
}

function dispProperties()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcShtNameStr = copyProperties.getProperty('SourceSheetName');
  var srcShtRangeStr = copyProperties.getProperty('SourceSheetRange');
  var desShtNameStr = copyProperties.getProperty('DestinationSheetName');
  var desShtRangeStr = copyProperties.getProperty('DestinationSheetRange');
  var title = 'Copy From To Sheets Properties';
  var msg = 'Source Sheet Name = ' + srcShtNameStr + '<br />';
  msg += 'Source Sheet Range = ' + srcShtRangeStr + '<br />';
  msg += 'Destination Sheet Range = ' + desShtNameStr + '<br />';
  msg += 'Destination Sheet Range = ' + desShtRangeStr + '<br />';
  msg += '<input type="button" value="Exit" onClick="google.script.host.close();" />';
  dispStatus(title,msg);
}

function copyFromToSheets()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(copyProperties.getProperty('SourceSheetName')).getRange(copyProperties.getProperty('SourceSheetRange'));
  var srcA = srcRange.getValues();
  srcRange.setBackground('#ffffff');
  var desRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(copyProperties.getProperty('DestinationSheetName')).getRange(copyProperties.getProperty('DestinationSheetRange'));
  desRange.setValues(srcA);
  desRange.setBackground('#ffffff');
}

function cutnpasteFromToSheets()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(copyProperties.getProperty('SourceSheetName')).getRange(copyProperties.getProperty('SourceSheetRange'));
  var srcA = srcRange.getValues();
  srcRange.clearContent();
  srcRange.setBackground('#ffffff');
  var desRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(copyProperties.getProperty('DestinationSheetName')).getRange(copyProperties.getProperty('DestinationSheetRange'));
  desRange.setValues(srcA);
  desRange.setBackground('#ffffff');
}

function setCopySource()
{
  var srcShtName = SpreadsheetApp.getActiveSheet().getName();
  var srcShtRange = SpreadsheetApp.getActiveRange();
  var copyProperties = PropertiesService.getDocumentProperties();
  copyProperties.setProperty('SourceSheetRange', srcShtRange.getA1Notation());
  copyProperties.setProperty('SourceSheetName', srcShtName);
  srcShtRange.setBackground('#d9caa9');
}

function setCopyDestination()
{
  var desShtName = SpreadsheetApp.getActiveSheet().getName();
  var desShtRange = SpreadsheetApp.getActiveRange();
  var copyProperties = PropertiesService.getDocumentProperties();
  copyProperties.setProperty('DestinationSheetRange',desShtRange.getA1Notation());
  copyProperties.setProperty('DestinationSheetName', desShtName);
  desShtRange.setBackground('#c4df87');
}

function clearCopyProperties()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcShtNameStr = copyProperties.getProperty('SourceSheetName');
  var srcShtRangeStr = copyProperties.getProperty('SourceSheetRange');
  var desShtNameStr = copyProperties.getProperty('DestinationSheetName');
  var desShtRangeStr = copyProperties.getProperty('DestinationSheetRange');
  if(srcShtNameStr && srcShtRangeStr)
  {
    var srcShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(srcShtNameStr).getRange(srcShtRangeStr);
    srcShtRange.setBackground('#ffffff');
  }
  else
  {
    SpreadsheetApp.getUi().alert('At least one of the Source String Properties is undefined in clearCopyProperties so background color cannot be reset.');
  }
  if(desShtNameStr && desShtRangeStr)
  {
    var desShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(desShtNameStr).getRange(desShtRangeStr);
    desShtRange.setBackground('#ffffff');
  }
  else
  {
    SpreadsheetApp.getUi().alert('At least one of the Destination String Properties is undefined in clearCopyProperties so background color cannot be reset.');
  }
  copyProperties.setProperty('SourceSheetName', '');
  copyProperties.setProperty('SourceSheetRange', '');
  copyProperties.setProperty('DestinationSheetName', '');
  copyProperties.setProperty('DestinationSheetRange', '');
}

function copyFromToSetupUi()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcShtNameStr = copyProperties.getProperty('SourceSheetName');
  var srcShtRangeStr = copyProperties.getProperty('SourceSheetRange');
  var desShtNameStr = copyProperties.getProperty('DestinationSheetName');
  var desShtRangeStr = copyProperties.getProperty('DestinationSheetRange');
  var title='No Title';
  var msg = 'No Text';
  if(!srcShtNameStr || !srcShtRangeStr )  //if !src
  {
    title = 'Select Source Range';
    msg = '<p>Please select input range from <strong>Source Sheet.</strong> and then press "Source Range Selected" button below.</p>\
    <br /><input type="button" value="Source Range Selected" onclick="google.script.run.copyFromToSetupHelper(1);google.script.host.close();" />';
    msg += '<script>console.log(\'flag1\');</script>';
    dispStatus(title, msg);
  }
  if ((srcShtNameStr && srcShtRangeStr) && (!desShtNameStr || !desShtRangeStr)) //if src and !des
  {
      var srcShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(srcShtNameStr).getRange(srcShtRangeStr);
      title = 'Select Destination Range';
      msg = '<p>Please select a destination range which is ' + srcShtRange.getNumRows() + ' rows by ' + srcShtRange.getNumColumns() + ' columns.</p>';
      msg += '<br /><input type="button" value="Destination Range Selected" onclick="google.script.run.copyFromToSetupHelper(2);google.script.host.close();" />';
      msg += '<br />Input Range: ' + srcShtRangeStr + '<br /><input type="button" value="Clear Ranges and Start Over" onClick="google.script.run.clearCopyProperties();google.script.host.close(); />';
      dispStatus(title, msg);
  }
  if((srcShtNameStr && srcShtRangeStr) && (desShtNameStr && desShtRangeStr))//if src and des
  {
    var srcShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(srcShtNameStr).getRange(srcShtRangeStr);
    var desShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(desShtNameStr).getRange(desShtRangeStr);
    if((desShtRange.getWidth()===srcShtRange.getWidth()) && (desShtRange.getHeight()===srcShtRange.getHeight()))
    {
      title= 'Displaying Source and Destination Ranges';
      msg = '<br />Source Sheet/Range: ' + srcShtNameStr + '/' + srcShtRangeStr + '<br />Destination Sheet/Range: ' + desShtNameStr + '/' + desShtRangeStr + '<br />';
      msg += '<br /><input type="button" value="Perform Copy" onclick="google.script.run.copyFromToSheets();google.script.host.close();" />';
      msg += '<br /><input type="button" value="Perform Cut & Paste" onclick="google.script.run.cutnpasteFromToSheets();google.script.host.close();" />';
      msg += '<br /><input type="button" value="Keep both Ranges Defined" onclick="google.script.host.close();" />';
      msg += '<br /><input type="button" value="Clear Ranges and Start Over" onclick="google.script.run.clearCopyProperties();google.script.host.close();" />';
      dispStatus(title,msg);
    }
    else
    {
      var srcShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(srcShtNameStr).getRange(srcShtRangeStr);
      var desShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(desShtNameStr).getRange(desShtRangeStr);
      var newdesShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(desShtNameStr).getRange(desShtRange.getRow(), desShtRange.getColumn(), srcShtRange.getNumRows(), srcShtRange.getNumColumns());
      desShtRange.setBackground('white');
      newdesShtRange.setBackground('#c4df87');
      copyProperties.setProperty('DestinationSheetRange', newdesShtRange.getA1Notation());
      title = 'Destination Range Adjusted';

      msg = 'Source Range and Destination Range Dimension did not Match. So it was assumed that the upper left corner of the Destination Range is correct';
      msg += 'and that the Sheet Selections were correct. The Destination Range was modified to have the same dimensions as the Source Range. ';
      msg += '<br />Source Sheet/Range: ' + srcShtNameStr + '/' + srcShtRangeStr + '<br />Destination Sheet/Range: ' + desShtNameStr + '/' + newdesShtRange.getA1Notation() + '<br />';
      msg += '<br /><input type="button" value="Perform Copy" onclick="google.script.run.copyFromToSheets();google.script.host.close();" />';
      msg += '<br /><input type="button" value="Perform Cut & Paste" onclick="google.script.run.cutnpasteFromToSheets();google.script.host.close();" />';
      msg += '<br /><input type="button" value="Keep both Ranges Defined" onclick="google.script.host.close();" />';
      msg += '<br /><input type="button" value="Clear Ranges and Start Over" onclick="google.script.run.clearCopyProperties();;google.script.host.close(); />';
      dispStatus(title,msg);

    }


  }
}


function copyFromToSetupHelper(mode)
{
  var mode = (typeof(mode) !== 'undefined')? mode : 0;
  switch(mode)
  {
    case 1:
      setCopySource();
      copyFromToSetupUi();
      break;
    case 2:
      setCopyDestination();
      copyFromToSetupUi();
      break;
    default:
      clearCopyProperties();
  }
}
// Display a modeless dialog box with custom HtmlService content.
function dispStatus(title,html,width,height)
{
  var title = typeof(title) !== 'undefined' ? title : 'No Title Provided';
  var width = typeof(width) !== 'undefined' ? width : 400;
  var height = typeof(height) !== 'undefined' ? height : 300;
  var html = typeof(html) !== 'undefined' ? html : '<p>No html provided.</p>';
  var htmlOutput = HtmlService
     .createHtmlOutput(html)
     .setWidth(width)
     .setHeight(height);
 SpreadsheetApp.getUi().showModelessDialog(htmlOutput, title);
} 



回答3:


Google Script: Moves active selection range any direction

This will shift any selected range any direction you wish and it can select the destination range as the active selection. I've only tried it for one cell step moves so far.

function rangeJog(hoffset,voffset,moveselection)
{
  var hoffset = (typeof(hoffset) !== 'undefined')? hoffset : 1;
  var voffset = (typeof(voffset) !== 'undefined')? voffset : 0;
  var moveselection = (typeof(moveselection) != 'undefined')? moveselection : true;
  var src = SpreadsheetApp.getActiveRange();
  var srcA1 = src.getA1Notation();
  var row = src.getRow() + voffset;
  var col = src.getColumn() + hoffset; 
  var rows = src.getLastRow() - src.getRow() + 1; 
  var cols = src.getLastColumn() - src.getColumn() +1;  

  if((row<1) || (col<1))
  {
    //dispStatus('No More Room to Move','<p>Either the first row or the first column or both will be less than one. <input type="button" value="exit" onClick="google.script.host.close();" /></p>', 400, 200);
    SpreadsheetApp.getUi().alert('No more room to move.');
  }
  else
  {
    var des = SpreadsheetApp.getActiveSheet().getRange(src.getRow() + voffset, src.getColumn() + hoffset, src.getLastRow() - src.getRow() + 1, src.getLastColumn() - src.getColumn() +1);
    var srcA = src.getValues();
    src.clearContent();
    des.setValues(srcA);
    if(moveselection)
    {
      SpreadsheetApp.getActiveSheet().setActiveSelection(des);
    }
  }
  var end = "is near";
}

It works on the selected range for now but any range could work because all calculations are relative to the src range. I also modified it to move the selection if moveselection is true. If you have trouble return and I'll try to help you out.

But the idea of inserting a new column to the left is perhaps a simpler way to go. Although I don't see any insert cells command so inserting a column will move your headers around as well. So I'll leave this here if you want it you can have it.



来源:https://stackoverflow.com/questions/42284258/shift-cell-range-in-google-sheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!