简体   繁体   中英

VBA to find the font color of a string

I am new to VBA..I am writing a macro for some file comparison..My requirement is if a string has red color font,that string should be ignored for iteration and code should move to next iteration..I have tried the following code.

Dim compare = {"test1","test2","test3",.....etc}

i=0

For j=1 to Ubound(compare)    
  j=1

  If compare.Characters(j,Len(compare(i))).Font.Color <> vbRed Then    
    ' Some Code
  End If

  i=i+1    
Next

However during the execution I am getting runtime error 424 "Object Required.Please help me to complete this task

Thanks in advance.

Say we have cells A1 thru A4 like:

PIC

Then this code will find the non-red characters:

Sub ColorTest()
    Dim I As Long, J As Long
    For I = 1 To 4
        For J = 1 To Len(Cells(I, 1).Value)
            If Cells(I, 1).Characters(Start:=J, Length:=1).Font.Color <> vbRed Then
                MsgBox "non-red found at cell A" & I & " position " & J
            End If
        Next J
    Next I
End Sub

May I assume that the source for your data is an excel-sheet (as pointed out by previous comments, a pure string does not hold information on colours), and for one reason or another you want to use an array. Then this might be a way to solve the problem (prerequisite: full string is in one colour only)

(Just saw that there's a solution provided by Gary's student without using arrays as well...AND providing for cases where only part of the string is red...nice one!)

 Sub colour() Dim arr_DB As Variant Dim i As Long ReDim arr_DB(1, 1) 'Array size to be adjusted as needed, Base 0 ! For i = 1 To 2 arr_DB(i - 1, 0) = ActiveSheet.Cells(i, 1).Value 'Value of Cell arr_DB(i - 1, 1) = ActiveSheet.Cells(i, 1).Font.Color 'Colour of Font in Cell Next If arr_DB(i - 1, 1) = 255 Then ' No. 255 is colour RED 'skip..... End If End Sub 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM