简体   繁体   中英

VBA: Format and change cell value based on specific values in cell

I would like the below to change the value of the particular cell to "Rank" if two consecutive cells in the column are "#Name"

In addition, it would be helpful if the formatting of the cell could be red and font color white, while the value in the preceding cell would be nothing, and color blue

This is what I wrote but it isn't working, really appreciate guidance-

Sub FormatRankColmn()
'
' FormatRankColmn Macro
'

'
Dim cell As Range

For Each cell In Range("D1:D250").SpecialCells(xlCellTypeConstants)

If cell.Offset(-1, 0).Value = "#NAME" Then
    If cell.Value = "#Name" Then
        Range(cell).Value = "Rank"
    End If
End If
Next
End Sub

You need to check for cell in first row, otherwise this raise an error (no cell in row 0): cell.Offset(-1, 0)

I believe this is what you are after:

Sub FormatRankColmn()

Dim cell As Range

For Each cell In Range("D1:D250").SpecialCells(xlCellTypeConstants)

If cell.Value = "#NAME" And cell.Row <> 1 Then
    If cell.Offset(-1, 0).Value = "#NAME" Then
        cell.Value = "Rank"
    End If
End If
Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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