3

I found a little macro to change all the text between "[" and "]" red in excel. But i can't get it to work in Excel 2010, i get some errors.

Can someone help me debug this? At the end i wish that in my excel sheets everything that is between "[" and "]" changes in font to red and everything thats outside of these criteria is still black.

This is the script i found on this site:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim Text As String
    Dim Index1 As Long
    Dim Index2 As Long
    Text = Target.Text
    Index2 = 1
    Do
        Index1 = InStr(Index2, Text, "[")
        If Index1 = 0 Then Exit Do
        Index2 = InStr(Index1, Text, "]")
        If Index2 = 0 Then Exit Do
        Target.Characters(Index1, Index2 - Index1 + 1).Font.Color = &HFF
    Loop
End Sub
1
  • Without knowing the error, it's impossible to say for sure, but I've given it a shot below.
    – j_foster
    Commented May 25, 2015 at 19:24

2 Answers 2

1

Consider:

Sub ColorMeRed()
   Dim r As Range, v As String, L As Long
   Dim RedMe As Boolean, i As Long
   For Each r In ActiveSheet.UsedRange
      v = r.Text
      If InStr(v, "[") > 0 Then
         L = Len(v)
         RedMe = False
         For i = 1 To L
            If r.Characters(i, 1).Text = "[" Then
               RedMe = True
            ElseIf r.Characters(i, 1).Text = "]" Then
               RedMe = False
            Else
               If RedMe Then r.Characters(i, 1).Font.Color = vbRed
            End If
         Next i
      End If
   Next r
End Sub

For example:

enter image description here

4
  • The code seems good thx alot, can i also add an option for between these {*} and als to be marked red? I thought of the "or" function but then i get the debug again.
    – Dubblej
    Commented May 26, 2015 at 10:55
  • @Dubblej The code would have to be modified from a dual-character if to a flp-flop if. Commented May 26, 2015 at 10:59
  • I searched for the flp-flop if, could you give me a reference where i can find info about it? Then i will post the code here if i'm done for people with a similar request.
    – Dubblej
    Commented May 26, 2015 at 12:02
  • @Dubblej I will update my Answer later today. Commented May 26, 2015 at 12:04
0

Change the line

Index1 = InStr(Index2, Text, "[")

to

Index1 = InStr(Text, "[")

The first version is trying to start searching at the position of Index2. Since Index2 has not had a value assigned, it equals 0; but InStr considers the first character of the string to be character 1. The changed version just has InStr start at the beginning of the string.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .