更改Excel单元格中的特定数值

时间:2016-06-08 20:10:18

标签: excel vba

我想为一个字符串中的1和0着色,例如" 1001001001"使用VBA宏作为两种不同的颜色。这可能吗? 这是我尝试过的代码

Sub changeTextColor()

     Green = RGB(0, 255, 0)
     Red = RGB(255, 0, 0)
     Black = RGB(0, 0, 0)

     'Select cell
     Range("H2").Select

     For x = 1 To 10
         If ActiveCell.Value = "1" Then

            'Change the text color if "1"

             ActiveCell.Font.Color = Green   

         ElseIf ActiveCell.Value = "0" Then

             'Change the text color if "0"

             ActiveCell.Font.Color = Red

         End If

         ActiveCell.Offset(1, 0).Select
     Next
 End Sub

1 个答案:

答案 0 :(得分:0)

这样的事情:

Sub changeTextColor()

    Dim v, s, clr, rng, x

    Set rng = Range("H2")


    Do While rng.Value <> ""
        v = rng.Value
        For x = 1 To Len(v)

            Select Case Mid(v, x, 1)
               Case "1": clr = vbGreen
               Case "0": clr = vbRed
               Case Else: clr = vbBlack
            End Select

            rng.Characters(x, 1).Font.Color = clr

        Next x

        Set rng = rng.Offset(1, 0)
    Loop
End Sub