Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Excel - using COUNTIF to find a value in a string?

Status
Not open for further replies.

sbroomfield

Programmer
Dec 7, 2000
13
US
I have a table which has single values ('A', 'B', 'C', etc)
in each cell. To summarise each row I have a formula like:
=COUNTIF(C7:AF7,"P"). This gives me all the occurrences of P in that row.
I have now had to change the table so that it includes more than one value in a cell ('AFH', 'BC', 'PLG').
How can I still get all the occurrences of P? I've trawled through Excel Help but I can't seem to find a way of checking to see if a letter occurs in a string!

Many Thanks.
 
Insert this function into a module on the workbook then you can use the function of CountK

Syntax =COUNTIFK(Range,Value)

Example :

=COUNTIFK(C7:AF7,"P") This would do what you want.

Public Function COUNTIFK(MyRange As Range, MyVal As Variant)
Dim Counter As Integer
Counter = 0

For Each c In MyRange

If InStr(1, c, MyVal) <> 0 Then
Counter = Counter + 1
End If
Next

COUNTIFK = Counter
End Function
 
This is case sensitive let me know if you want me to change it.
 
That means it can't find the function.

Did you place it in a module on the workbook you are trying to use the Function?

If you go to Insert-Function there should be a option in the Function category called &quot;User defined&quot; with the new function. If it doesn't appear you have place the function in the wrong place.

Let me know if you can't find it.
 
DarkSun : In case sbroomfield can't get the function stuff to work, I think the following formula will count the occurances - so long as there is only ONE instance of &quot;P&quot; in each cell (which is probably OK in this case).

{=COUNT(FIND(&quot;P&quot;,C7:AF7))}

Note : This function needs to be entered with Ctrl+Enter

Your macro code is a much better way to handle all the occurances of a string. I will definately keep it around for my use! BTW, I learn more from looking at your code than anywhere else - you really know your stuff. :)
 
Thanks JVFriederick, I was trying to find the Excel way to do it but got bored looking.
 
Thanks for all your help, guys.
The VBA code worked in the end.
 
DarkSun,

Isn't Dim c As Object required?

I needed to add it to get the CountIfK function to work in Office 97.


Dave
 
It's not required, it's wise to put it in. I'm using 97 as well.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top