我对这一切都很陌生,所以如果我很愚蠢,我现在会道歉。我在使以下代码正常运行时遇到了一些问题。基本上,我要求它查看一列;
- 如果单元格为空 = 白色
- 如果单元格值 = 到相邻列中的单元格,则颜色为白色
- 如果单元格值>到相邻列中的单元格,则颜色为红色
- 如果单元格值<到相邻列中的单元格,则颜色为绿色。>
当我运行下面的代码时,它会将所有单元格变成红色,有人能解释我错过了什么吗?
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