我使用以下代码通过检查其他单元格的值在单个单元格中追加值。我接下来要做的是更改我追加的值的字体颜色,并保留任何现有的字体颜色。例如:a1的值是“”。然后我将值“abc”追加为绿色。然后我将值“123”添加为红色。我希望细胞显示:
[(红色)(绿色)]
[“abc 123”]
我的代码:
If Cells(ActiveCell.Row, 6).Value = "Control" Then
bit_value = "(" & Application.WorksheetFunction.VLookup(Cells(ActiveCell.Row, 5).Value, Range("Output"), total_bits + 3, False) & ")" & high_low & " "
Cells(ActiveCell.Row, 7).Value = Cells(ActiveCell.Row, 7).Value & bit_value
End If
我的数据:
504003 Control 2 11 55 12 21 00010001 01010101 00010010 00100001
504003 Control 2 11 55 12 20 00010001 01010101 00010010 00100000
更新 通过使用Tim的代码,我得出了下面的更改,它完全符合我的需要。
bitColor = IIf(ActiveCell.Value = 0, RGB(255, 0, 0), RGB(0, 0, 255))
If Cells(ActiveCell.Row, 6).Value = "Control" Then
With Cells(ActiveCell.Row, 7)
bit_value = "(" & Application.WorksheetFunction.VLookup(Cells(Active _
Cell.Row, 5).Value,Range("Output"), total_bits + 3, False) & ")"
AddValue Cells(ActiveCell.Row, 7), bit_value, bitColor
End With
End If
答案 0 :(得分:1)
以下是如何在不丢失任何现有格式的情况下向单元格添加文本:
Sub Tester()
With ActiveSheet
AddValue .Range("A1"), "Hello", vbRed
AddValue .Range("A1"), "Hello", vbGreen
AddValue .Range("A1"), "Hello", vbBlue
End With
End Sub
Sub AddValue(rngVal As Range, val, theColor As Long)
Const SEP As String = " "
Dim firstChar As Long, extra As Long
firstChar = 1 + Len(rngVal.Value)
extra = IIf(firstChar = 1, 0, 1)
With rngVal
.Characters(firstChar).Text = IIf(Len(rngVal.Value) > 0, SEP, "") & val
.Characters(firstChar + extra, Len(val)).Font.Color = theColor
End With
End Sub
注意:使用此方法最多只能获得255个字符