使用Google Script

时间:2018-08-29 20:25:53

标签: loops google-apps-script google-sheets range highlight

我想编写一个脚本,使我只突出显示(选定背景范围内的)选定范围内的某些单元格,例如,即使选择了整个表格,也仅突出显示COLUMN 2和ROW 2中的单元格。

例如: How the script is supposed to work

例如:

For each cell in selected range {
	If selected cell[i][j] is within allowed range {
		cell background color = green
	};
};

我要完成的代码:

function BackgroundColor() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet = spreadsheet.getActiveSheet();
  var range = sheet.getActiveRange();
  var cells = range.getValues();
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  
  for (var i = 0; i < numRows; i++) {
    for (var j = 0; j < numCols; j++) {
      if (range.getValues()[i][j] == '') {
        range.setBackground('#00B050').setFontColor('#ffffff')
      }
    }
  }
  range.setValues(cells);
};

我能够在VBA中做到这一点

Sub cmdGreen()

    Dim Cel As Range
    Dim GreenArrayCount As Integer
    Dim InteriorColor As Long, FontColor As Long
    Dim GreenArray() As Variant
    Dim BodyRange As String

    InteriorColor = VBA.RGB(0, 176, 80) 'interior in green
    FontColor = VBA.RGB(255, 255, 255) 'font in white
    GreenArray = Array("COLUMN 2", "ROW 2")
    BodyRange = ActiveSheet.ListObjects(1).DataBodyRange.Address

    For Each Cel In Application.Selection.Cells
        If Not Intersect(Cel, Range(BodyRange)) Is Nothing Then
            For GreenArrayCount = LBound(GreenArray) To UBound(GreenArray)
                If (ActiveSheet.ListObjects(1).HeaderRowRange(Cel.Column).Value _
                    = GreenArray(GreenArrayCount) Or _
                    ActiveSheet.ListObjects(1).DataBodyRange(Cel.Row - 1, 1).Value _
                    = GreenArray(GreenArrayCount)) Then
                    Cel.Interior.Color = InteriorColor
                    Cel.Font.Color = FontColor
                End If
            Next GreenArrayCount
        End If
    Next Cel

End Sub

请问有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

毫无疑问,有很多方法可以提高性能,但这应该可以解决问题。

function BackgroundColor() {
  var okRow = 2;
  var okColumn = 2;
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet = spreadsheet.getActiveSheet();
  var selection = sheet.getSelection();

  //Logger.log('Active Range: ' + selection.getActiveRange().getA1Notation());

  var range = selection.getActiveRange();
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  var startRow = range.getRow();
  var startCol = range.getColumn();
  //Logger.log('row: ' + startRow);
  //Logger.log('col: ' + startCol);
  //Logger.log('num row: ' + numRows);
  //Logger.log('num col: ' + numCols);

  for (var i = 0; i < numRows; i++) {
    for (var j = 0; j < numCols; j++) {
      if ((startRow+i == okRow) || (startCol+j == okColumn)){
        //Logger.log('found: ' + i+' '+j);
        range.getCell(i+1,j+1).setBackground('#00B050').setFontColor('#ffffff')
      }
    }
  }
};

请注意,范围是基于0的,而getCell是基于1的。 还要注意,我的确定行和列是基于实际的行和列,而不是基于其标签。在您的示例中,okRow为4,okColumn为3。