下面的代码用于将单元格A中的值减半(其中B列中对应的单元格在3以上)。是否有任何方法也以红色突出显示单元格(基于相同的条件)。因此,如果B列中对应的单元格高于3,则将其减半并突出显示为红色:
Sub halveandcolorchange()
Dim cell As Range, rng As Range, A As Range, LastRow As Long
LastRow = Cells(Rows.Count, "B").End(xlUp).Row
Set rng = Range("B1:B" & LastRow)
For Each cell In rng
Set A = cell.Offset(0, -1)
If cell.Value > 3 Then A.Value = A.Value / 2
Next cell
End Sub
请完全限定您的范围,Excel将假设您指的是ActiveWorkbook
和ActiveSheet
,这可能不是您的意图。
。ThisWorkBook.Sheets("Sheet1").Range("B1:B" & LastRow)
Sub halveandcolorchange()
Dim cell As Range, rng As Range, A As Range, LastRow As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sales")
LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
Set rng = ws.Range("B1:B" & LastRow)
For Each cell In rng
Set A = cell.Offset(0, -1)
If cell.Value > 3 Then
A.Value = A.Value / 2
A.Interior.ColorIndex = 3
End If
Next cell
End Sub