首页 > 解决方案 > 在 Google 脚本中将值从一列复制到另一列

问题描述

我有一个数据表,它从谷歌表格中的一系列 VLOOKUP 中提取其信息。我不断编辑更改我的数据表的源。我需要一个谷歌脚本代码,它将受公式影响的单元格复制到另一个不会受到影响的列。我尝试一次复制所有内容以移动,但第二次激活时,现在的空白单元格覆盖了以前我能够使用 VBA 成功完成此任务的单元格,但我无法弄清楚过渡。这是我到目前为止所拥有的:

function CopyCells() {

var sheet2 = SpreadsheetApp.getActive().getSheetByName('Records');
var loc = sheet2.getRange("C2:C126").getValues();
var taget_sheet = sheet2.getRange("D2:D126");
for(i = 1;i == "Present";i++){ i.copyTo("target_sheet")}       
}

我的 VBA 代码:

 Dim ColERange As Range
 Dim ColFRange As Range 
 Set ColERange = Range("E1:E100") 
 Set ColFRange = Range("F1:F100") 
 Dim Cell As Range 
 For Each Cell In ColERange 
   If Cell.Value = "Present" 
     Then Cell.Offset(0, 1).Value = Cell.Value 
   ElseIf Cell.Value = "Absent" 
     Then Cell.Offset(0, 1).Value = Cell.Value 
   ElseIf Cell.Value = "" 
     Then Cell.Offset(0, 1).Value = Cell.Value 
   End If 
 Next Cell   

标签: google-apps-scriptgoogle-sheets

解决方案


尝试这个:

/*
 Dim ColERange As Range
 Dim ColFRange As Range 
 Set ColERange = Range("E1:E100") 
 Set ColFRange = Range("F1:F100") 
 Dim Cell As Range 
 For Each Cell In ColERange 
   If Cell.Value = "Present" 
     Then Cell.Offset(0, 1).Value = Cell.Value 
   ElseIf Cell.Value = "Absent" 
     Then Cell.Offset(0, 1).Value = Cell.Value 
   ElseIf Cell.Value = "" 
     Then Cell.Offset(0, 1).Value = Cell.Value 
   End If 
 Next Cell   
*/    

我认为这个版本是您想要的,因为只需更改一件事,您就可以更改您复制到的列..

function CopyCells1(col) {
  var col=col || 1;
  var sh=SpreadsheetApp.getActive().getSheetByName('Records');
  var rg1=sh.getRange("C2:C126");
  var vA=rg1.getValues();
  var rg2=rg1.offset(0, col);//Changing the column offset allows you to gain access to the other columns. Note: it can be negative.
  var vB=rg2.getValues();
  for(var i=0;i<vA.length;i++){
    if((vA[i][0]=='Present')||(vA[i][0]=='Absent')){
      vA[i][0]=vB[i][0];
    }
  }
  rg2.setValues(vB);
}

推荐阅读