VBA: Count number of words in cell not black

FryGirl

Well-known Member
Joined
Nov 11, 2008
Messages
1,364
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
In cell G2 I have a sentence; however, a certain number of those words are colored with red font. Not by CF; rather, they are manually colored.

In cell H2 I have a formula to count the total number of words in that sentence. =LEN(G2)-LEN(SUBSTITUTE(G2" ",""))+1

There are a few words in that sentence that are not black. How can I count the non-black cells? Also, this is not just for cell G2. I will be applying this down G2 for a couple of thousand rows.
 

Excel Facts

How to find 2nd largest value in a column?
MAX finds the largest value. =LARGE(A:A,2) will find the second largest. =SMALL(A:A,3) will find the third smallest
Try:

VBA Code:
Sub CountNonBlack()
Dim r As Long, w As String, ctr As Long, MyLoc As Long

    For r = 2 To Range("G2").End(xlDown).Row
        w = Cells(r, "G").Value
        ctr = 0
        MyLoc = 1
        While MyLoc > 0
            If Cells(r, "G").Characters(Start:=MyLoc, Length:=1).Font.Color <> vbBlack Then ctr = ctr + 1
            MyLoc = InStr(MyLoc, w, " ")
            If MyLoc > 0 Then MyLoc = MyLoc + 1
        Wend
        Cells(r, "H") = ctr
    Next r
End Sub

Book1
GH
1
2This is a test.1
3The quick brown fox is red.3
4Don't count this.0
5
Sheet41


XL2BB doesn't capture color changes within a cell, but the words "test", "The", "brown", and "red" were red in my test example.
 
Upvote 0
Solution
Thanks Eric. This works absolutely fantastic!
 
Upvote 0

Forum statistics

Threads
1,215,429
Messages
6,124,834
Members
449,192
Latest member
mcgeeaudrey

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top