excel - 更改数字中最后 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) 变量的字体颜色。
解决方案
此方法为您提供了更多选择:
您将范围参考和可选的字符数和 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 过程中所示)。
推荐阅读
- python - 消息被编辑时如何对其做出反应
- jquery - 如何在上传前显示图像?
- c++ - 存储参数和函数并在另一个函数中使用它们
- javascript - 使每组中的 1 个随机图层可见的脚本 [Photoshop cc2018]
- json - 在使用 Flutter Local Notifications 和 Workmanager 使用 API 发送通知时需要帮助
- asp.net - .aspx 在 URL 的末尾
- css - 图标不显示?
- html - 旋转元素时,具有透明背景的 div 中出现意外的灰线
- python - 如何在 Jupyter Notebook 单元格中刷新 Python 导入?
- java - java模块问题“模块'mp3player'从'javafx.graphics'和'javafx.graphics'读取包'javafx.animation'”