繁体   English   中英

Excel VBA-基于单元格值的格式(大于,小于,等于)

[英]Excel VBA - Format based on cell value (Greater than, less than, equal to)

我对所有这些都还很陌生,所以如果我很愚蠢,我现在会道歉。 我在使以下代码正常运行时遇到一些问题。 基本上,我要它只看一栏,

  1. 如果单元格为空=白色
  2. 如果单元格值为=到相邻列中的单元格,则颜色为白色
  3. 如果单元格值>到相邻列中的单元格,则颜色为红色
  4. 如果单元格值小于相邻列中的单元格,则为绿色。

当我运行以下代码时,所有单元格都变成红色,有人能解释我错过的内容吗?

    Sub Format_Cells()
    Dim arq As Range
    Dim msl As Range
    Dim Cell

    Set arq = Range("B3:B500")
    Set msl = Range("C3:C500")

    For Each Cell In arq
    'If Cell is blank then Cell Colour = White
        If Cell.Value = "" Then
            Cell.Interior.ColorIndex = 2
        End If
    'If Requisition Quantity is equal to Max Stock Level then Cell Colour = White
        If arq(B3) = msl(C3) Then
            Cell.Interior.ColorIndex = 2
        End If
    'If Requisition Quantity is less than Max Stock Level then Cell Colour = Green
        If arq(B3) < msl(C3) Then
            Cell.Interior.ColorIndex = 43
        End If
    'If Requisition Quantity is more than Max Stock Level then Cell Colour = Red
        If arq(B3) > msl(C3) Then
            Cell.Interior.ColorIndex = 46
        End If

    Next

     MsgBox "The macro has finished running.", vbInformation
 End Sub

如上所述,CF可能是可行的方法,但是您以现有的代码为起点,我刚刚修改为使用Offset(在右边的1列)。 您的四个条款是否互斥?

Sub Format_Cells()

Dim arq As Range
Dim msl As Range
Dim Cell As Range

Set arq = Range("B3:B500")
Set msl = Range("C3:C500")

For Each Cell In arq
'If Cell is blank then Cell Colour = White
    If Cell.Value = vbnullstring Then
        Cell.Interior.ColorIndex = 2
    End If
'If Requisition Quantity is equal to Max Stock Level then Cell Colour = White
    If Cell.Value = Cell.Offset(, 1).Value Then
        Cell.Interior.ColorIndex = 2
    End If
'If Requisition Quantity is less than Max Stock Level then Cell Colour = Green
    If Cell.Value < Cell.Offset(, 1).Value Then
        Cell.Interior.ColorIndex = 43
    End If
'If Requisition Quantity is more than Max Stock Level then Cell Colour = Red
    If Cell.Value > Cell.Offset(, 1).Value Then
        Cell.Interior.ColorIndex = 46
    End If
Next

MsgBox "The macro has finished running.", vbInformation

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM