0

我有一个单元格(例如 L22),其中有一个公式(引用另一张表(Sheet!1A22)并返回值 sale 110(108%)。我只想更改(108%)的文本颜色(而不是整个单元格值)。我的方法是使用 Instr 查找“(”并找到直到“)”的长度并为其着色。这是我使用的代码。

Sub colr()
Dim StartChar As Integer, LenColor As Integer
    With Flash.Range("L22")
        StartChar = InStr(1, .Value, "(")
        If StartChar <> 0 Then
            LenColor = Len(.Value) - StartChar + 1
            .Characters(Start:=StartChar, Length:=LenColor).Font.Color = RGB(255, 0, 0)
        End If

    End With
End Sub

但代码没有做任何事情。但是如果我用值替换公式,它就可以正常工作。

4

2 回答 2

0

正如其他人所评论的那样,不可能操纵Characters公式的结果 - 至少据我所知不是。

最明显的替代方法是在两个相邻单元格中写入值和百分比,然后对后者使用条件格式。

但是,如果您坚持使用现有格式,那么您将不得不解决公式问题。当任何引用的范围值发生更改时,基本上都会触发公式计算。您可以自己捕获该事件,例如在Worksheet_Change处理程序中并将算法的结果写入 Sheet2。这将使您能够为结果的字符着色。

骨架代码看起来像这样(在 Sheet1 对象中):

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim cell As Range
    Dim result As Variant
    Dim pt As Long

    For Each cell In Target.Cells
        'Test for a change in the desired range.
        If Not Intersect(cell, Me.Range("A:A")) Is Nothing Then
            'Check that your cell value matches the conditions you want, eg
            If IsNumeric(cell.Value) Then
                'Calculate the result - as per your cell formula.
                result = cell.Value * 2 & " (" & cell.Value * 2 / 100 & "%)"
                'Write and colour the result.
                pt = InStr(result, "(")
                With Sheet2.Cells(cell.Row, "L")
                    .Value = result
                    .Characters(pt, Len(result)).Font.Color = RGB(255, 0, 0)
                End With
            End If
        End If
    Next
End Sub
于 2020-01-27T00:14:04.807 回答
0

当你使用值时,它会给你实际的数字,但是对于文本,它会给你显示在单元格中。所以你可以改变:

StartChar = InStr(1, .Value, "(")

成为:

StartChar = InStr(1, .text, "(")
于 2020-01-27T06:42:42.607 回答