Excel - 仅在括号内有条件地格式化文本

时间:2021-01-04 09:17:10

标签: excel vba excel-formula conditional-formatting

条件格式应仅应用于括号内的文本。该公式还应基于括号内的内容(0 = 黑色,< 0 = 红色,> 0 = 绿色)。

如果没有 VBA,这可能吗?如果没有,VBA 解决方案就可以了。

enter image description here

在 PPT 报告中应该是什么样子:

enter image description here

1 个答案:

答案 0 :(得分:2)

请尝试下一个方法。有条件格式化的范围是“C1:C5”,就像我可以从您的示例中推断出的那样,但它可以适用于任何位置。代码还可以计算它的最后一个单元格:

Sub condFormattingStringParant()
 Dim sh As Worksheet, rng As Range, c As Range
 
 Set sh = ActiveSheet
 Set rng = sh.Range("C1:C5")
 For Each c In rng.cells
    If Not FormatCond(c) Then
        MsgBox "In cell " & c.Address & " no parentheses pattern could be found..."
    End If
 Next
End Sub

Function FormatCond(c As Range) As Boolean
    Dim vComp As Double, ar, startCh As Long, lngth As Long, col As Long
    
    startCh = InStr(c.Value, "(") + 1
    If startCh = 1 Then FormatCond = False: Exit Function
    ar = Split(c.Value, "(")
    lngth = Len(ar(1)) - 1
    
    vComp = CDbl(left(ar(1), Len(ar(1)) - 1))
    Select Case vComp
        Case Is > 0
             col = RGB(0, 150, 90)
        Case Is = 0
            col = vbBlack
        Case Else
            col = vbRed
    End Select
    c.Characters(startCh, lngth).Font.Color = col: FormatCond = True
End Function

请测试并发送一些反馈

相关问题