宏:获取第一行中单元格的颜色

时间:2018-04-09 06:28:48

标签: excel vba excel-vba

我的第一行有redgreen颜色的Excel。我想检查活动单元格的第一行中的颜色是否为红色。如果是红色,则显示消息"必填字段。"并将重点放在同一个单元格上。 红色的颜色指数是48。

enter image description here

示例算法:

If ActiveCell is C2 and it is empty, display message "Required field" and focusCell = C2
If ActiveCell is G2, do nothing 

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

将其放入模块中:

Function CellColor(ws As Worksheet, irow As Integer)

        Dim lcol As Integer
        Dim icol As Integer
        Dim ccell As Range

      'Gives last populated column in the row
      lcol = ws.Cells(irow, Columns.Count).End(xlToLeft).Column

      'Loops through each cell until last populated column
      For icol = 1 To lcol

          Set ccell = ws.Cells(irow, icol)

              If ccell.Interior.ColorIndex = 3 Then
                  MsgBox ccell.value & "is Red"
              ElseIf ccell.Interior.ColorIndex = 4 Then
                  MsgBox ccell.value & " is Green"
              Elseif ccell.value = "" then
                  ccell.value = "Required Field"
              End If

      Next

    End Function

调用Sheet1和第一行上的函数的示例:

Call CellColor(Sheet1, 1)

如果您想更改颜色但不知道什么是ColorIndex,只需在excel上选择一个单元格,然后在VBA立即窗口(ctrl + G)上运行您想要的颜色:

Msgbox activecell.Interior.ColorIndex

activecell或range,然后.Interior.ColorIndex将检索ColorIndex以供你在函数中使用。

如果您想知道绿色细胞或红细胞的地址,您可以替换:

MsgBox ccell.value & "is Red"

有关

MsgBox ccell.address & "is Red"
祝你好运!