Consulting

Results 1 to 6 of 6

Thread: Solved: Counting based on Cell Values

  1. #1
    VBAX Contributor
    Joined
    Feb 2007
    Posts
    126
    Location

    Cool Solved: Counting based on Cell Values

    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"


    [vba]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[/vba]

    Thanks a lot

    Mike

  2. #2
    VBAX Contributor moa's Avatar
    Joined
    Nov 2006
    Posts
    177
    Location
    Which type has "-d" in its name?
    Glen

  3. #3
    VBAX Contributor
    Joined
    Feb 2007
    Posts
    126
    Location

    Not sure what you mean

    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

  4. #4
    VBAX Contributor moa's Avatar
    Joined
    Nov 2006
    Posts
    177
    Location
    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...
    Glen

  5. #5
    VBAX Contributor moa's Avatar
    Joined
    Nov 2006
    Posts
    177
    Location
    I think you want
    [vba]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[/vba]
    Glen

  6. #6
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    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.
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •