Excel 2013中的#VALUE错误设置Interior.ColorIndex属性

时间:2018-05-29 15:37:03

标签: excel-vba vba excel

我试图遍历工作表中的行,在第11列中查找非零值,然后突出显示整行。我在这个站点上找到了这样做的例子,但是当我试图模仿这些例子时,我从函数返回了#VALUE错误。

代码如下:

 public void Pause() 
    {
        if (Time.timeScale == 1) 
        {
            Time.timeScale = 0;
        }
       else if (Time.timeScale == 0)
        {
            Time.timeScale = 1; //Resume Game..
        }
    }

当我注释掉试图设置代码的Interior.ColorIndex属性的代码时,一切似乎都正常工作,我得到函数返回的相应计数(当然除了我没有得到突出显示) )。

我也尝试了以下内容:

  • w.Cells(i,11).EntireRow.Interior.ColorIndex = 3
  • w.Range(“B”& i&“:O”& i).Interior.ColorIndex = 3
  • w.Range(Cells(i,2),Cells(i,15))。Interior.ColorIndex = 3

我错过了什么?

2 个答案:

答案 0 :(得分:2)

使用而不是功能

Sub HighlightRows()
    Dim c As Long
    Dim i As Long
    Dim w As Worksheet


    Set w = ThisWorkbook.Worksheets("Sheet1")
    c = 0
    For i = 2 To w.UsedRange.Rows.Count
        If w.Cells(i, 11).Value = 1 Then
            c = c + 1
            w.Rows(i).Interior.ColorIndex = 3
        End If
    Next i

    MsgBox c

End Sub

enter image description here

答案 1 :(得分:1)

如果有遗嘱,有办法:

Function DoHighlight(what As Integer)
    ThisWorkbook.Worksheets("Sheet1").Cells(what, 1).EntireRow.Interior.ColorIndex = 3
End Function

Function HighlightRows() As Long
    Dim c As Long
    Dim i As Long
    Dim w As Worksheet
    Set w = ThisWorkbook.Worksheets("Sheet1")
    c = 0
    For i = 2 To w.UsedRange.Rows.Count
        If w.Cells(i, 11).Value = 1 Then
            c = c + 1
            Evaluate ("DoHighlight(" & i & ")")
        End If
    Next i

    HighlightRows = c

End Function

这里的要点是通过从一个字符串中评估一段代码来绕过限制,该字符串将调用一个单独的函数来完成公式函数之外的工作。

注意:我建议不要这样做,因为某个原因禁用更改公式中的单元格格式。使用风险自负。