首页 > 解决方案 > 更改数字中最后 3 位的字体颜色

问题描述

我在 Excel VBA 中的一些代码遇到问题。

我有一个始终为 7 位数字的标识号,位于 B 列中。我需要获取标识号的最后 3 位数字并更改字体颜色。

我试过使用 Right() 函数,但我不知道如何将它与 Font.Color 函数结合起来。

Sub Test    

Dim i As Long
    
For i = 1 To 3
    RResult = Right(ActiveCell, 3)
    LResult = Left(ActiveCell, 4)
    ActiveCell = LResult + " " + RResult
    ActiveCell.Offset(1, 0).Select
Next i
    
End Sub

我尝试了上面的代码来分隔数字,但我无法更改 RResult (Right Result) 变量的字体颜色。

标签: excelvba

解决方案


此方法为您提供了更多选择:

您将范围参考和可选的字符数和 RGB 颜色传递给它。

Public Sub ColourLastThree(Target As Range, Optional CharCount As Long = 3, Optional RGBColour As Long = 255)

    Dim rCell As Range

    For Each rCell In Target
        If Len(rCell) >= CharCount Then
            rCell = "'" & rCell
            rCell.Characters(Start:=Len(rCell) - (CharCount - 1), Length:=CharCount).Font.Color = RGBColour
        End If
    Next rCell

End Sub

然后,您可以调用该过程:

'Colour the last three characters in the ActiveCell to red.
Sub Test()
    ColourLastThree ActiveCell
End Sub

'Colour last four characters in Sheet1!A1 to red.
Sub Test1()
    ColourLastThree Worksheets("Sheet1").Range("A1"), 4
End Sub

'Colour last four characters in Sheet1!A1 to Green.
Sub Test2()
    ColourLastThree Worksheets("Sheet1").Range("A3"), 4, RGB(0, 255, 0) 'or can use 65535 as RGB.
End Sub

'Colour last three character in each cell on the ActiveSheet in A1:A4.
Sub Test3()
    ColourLastThree Range("A1:A4")
End Sub

编辑: 我更新了代码以循环遍历传递的目标范围中的每个单元格(如 Test3 过程中所示)。


推荐阅读