PDA

View Full Version : Solved: Counting based on Cell Values



itipu
03-16-2007, 05:21 AM
Can't seem to figure out why this little code I wrote does not work...

Basically it should look through each cell in given range, and count all cells that contain "-d"


Sub CountRE()
Dim count As Integer
Dim cel As Range
Dim rng As Range

Set rng = Sheet6.Range("A1:A20")
count = 0
For Each cel In rng
If TypeName(cel.Value) = "*-d*" Then
count = count + 1
End If
Next
frmExtract.TextBox1.Value = count

End Sub

Thanks a lot

Mike

moa
03-16-2007, 05:31 AM
Which type has "-d" in its name?

itipu
03-16-2007, 05:33 AM
Not sure what you mean by type... but I have a column A which is a list of machine names, like abncd-d956959 for desktop, and ahaj-s09394 for server, so I just want to count those containing "-d' - desktops...

Thx

moa
03-16-2007, 05:37 AM
Oh, okay. VBA's TypeName() method returns the name of the type i.e. string or date.

Put a message box call in your loop and see what typeName(cel.Value) is returning...

moa
03-16-2007, 05:42 AM
I think you want
Sub CountRE()
Dim count As Long
Dim cel As range
Dim rng As range

Set rng = Sheet1.range("A1:A20")
count = 0
For Each cel In rng
If cel.Value Like "*-d*" Then
count = count + 1
End If
Next

End Sub

mdmackillop
03-16-2007, 06:33 AM
For small ranges, use Moa's solution. For large ranges, you would be better with Find, which avoids checking each cell. Check out FindNext in VBA Help for an example of looping.