简体   繁体   中英

Change font color of specific cell in a table

I have a VBA procedure that loops through the rows of an Excel table and updates cell values:

Public Sub LoadRecords()
    Dim n As Long
    With DataSheet.ListObjects(tblName)
        For n = 1 To .ListRows.Count
            If UCase(.ListColumns(colNameLoad).DataBodyRange(n).Value) = "Y" Then
                .ListColumns(colNameMessage).DataBodyRange(n) = response
            End If
        Next
    End With
End Sub

I want to enhance the code so that, in addition to updating the cell values, it also changes the cell font colour.

I can do this for the entire column:

.ListColumns(colNameMessage).Range.Font.colorIndex = 48

However, I can't figure out how to change the font colour of a specific cell/row from within the loop.

You're very close already. .ListColumns(colNameMessage).DataBodyRange(n) is the individual cell, so:

.ListColumns(colNameMessage).DataBodyRange(n).Value = response 
.ListColumns(colNameMessage).DataBodyRange(n).Font.ColorIndex = 48

As mentioned in a (now deleted) comment, it's preferable to use .Font.Color instead of .Font.ColorIndex , as the latter is just an index in the current palette , not an absolute color.

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