如何使用For .. Next Loop和Select Case进行颜色编码工作表?

时间:2017-01-02 19:46:42

标签: excel-vba runtime-error vba excel

我对VBA很新,并且很难调试下面的代码块。我的目标是根据第7列中单元格的内容对活动工作表中的某些行(比如说其中的5%)进行颜色编码。错误代码是运行时错误“1004”:应用程序定义的错误或对象定义的错误。任何帮助或指示将不胜感激。

编辑:lastRow在其他代码块中运行良好,并且在程序的早期声明和分配,因此我目前不怀疑它是问题。

' Color code data based on strings or numbers found in column 7
  Dim lastRow as Integer
  lastRow = 9,000
  Dim blockStatus As Variant

  For blockRow = 3 To lastRow
' the following row triggers runtime error    
    blockStatus = ActiveWorkbook.ActiveSheet.Range(Cells(blockRow, 7)).Value
      Select Case blockStatus
          Case Is = "ADMIN*"
          Range(Cells(blockRow, 1), Cells(blockRow, 11)).Font.Bold = True
          Case Is = "OTHER*"
          Range(Cells(blockRow, 1), Cells(blockRow, 11)).Font.Color = RGB(192, 0, 0)
          Case Is = "*@*"
          Range(Cells(blockRow, 1), Cells(blockRow, 11)).Font.Color = RGB(0, 176, 80)
          Case Else
      End Select
  Next blockRow

1 个答案:

答案 0 :(得分:0)

Absinthe的评论解决了您的错误(范围的参数可以是地址,也可以是两个单元格)。

我相信为什么你的代码没有达到预期的效果,你希望你的Case语句对所提到的字符串执行Like操作。

如果是,请按如下所示更改您的代码:

With ActiveSheet
    For blockRow = 3 To lastRow
        blockStatus = .Cells(blockRow, 7).Value
        With .Range(.Cells(blockRow, 1), .Cells(blockRow, 11))
            Select Case True
                Case blockStatus Like "ADMIN*"
                    .Font.Bold = True
                Case blockStatus Like "OTHER*"
                    .Font.Color = RGB(192, 0, 0)
                Case blockStatus Like "*@*"
                    .Font.Color = RGB(0, 176, 80)
                Case Else
            End Select
        End With
    Next blockRow
End With

(注意:无法执行Case Like "ADMIN*",这就是为什么我使用了Select Case TrueCase Case blockStatus Like "ADMIN*"这样的for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) System.out.println(deck[j * 5 + i]) 语句的原因。)