View Single Post
  #14   Report Post  
Posted to microsoft.public.excel.worksheet.functions
Ron Rosenfeld Ron Rosenfeld is offline
external usenet poster
 
Posts: 5,651
Default how to count if cell "contains" a word

On Mon, 14 Jul 2008 07:15:00 -0700, cjlatta
wrote:

Unfortunately, not all the values are four characters. Like the suggestion
though!
Thanks for the info.


What I meant to write is that the technique of using wild cards (or FIND or
SEARCH) will not differentiate: abcd from abcde (or from any string in which
abcd is a substring.

If this is an issue, you can use a UDF such as:

============================
Option Explicit
Function StringCount(rg As Range, str1 As String, str2 As String) As Double
Dim c As Range
Dim re As Object, mc As Object

Set re = CreateObject("vbscript.regexp")
re.Pattern = "(\b" & str1 & "\b.*\b" & str2 & _
"\b)|(\b" & str2 & "\b.*\b" & str1 & "\b)"

For Each c In rg
If re.test(c.Value) = True Then _
StringCount = StringCount + 1
Next c
End Function
=================================

To enter this UDF, <alt-F11 opens the VB Editor. Ensure your project is
highlighted in the project explorer window, then Insert/Module and paste the
code above into the window that opens.

To use this, enter a formula of the type:

=StringCount(A1:A10,"abcd","abcf")

The UDF requires that the two substrings be present (in any order) and it will
not count, for example, abcde when looking for abcd.
--ron