+ Reply to Thread
Results 1 to 4 of 4

Help with Simple Function

  1. #1
    Registered User
    Join Date
    08-31-2005
    Posts
    48

    Help with Simple Function

    Hi guys,

    Am new to this forum but could do with some help. I've just started working in a bank and need to sharpen up on my excel. I'm not new to programming, but am to VB and its syntax. Also I've never been very good at debugging.

    Anyway trying to write a simple function that takes a range then counts the number of time a string occurs in it. Heres my code:

    Function CountStr(ran As Range, Str As String) As Integer

    Dim temp As Integer
    temp = 0
    For Each x In ran
    If x = Str Then temp = temp + 1
    End If
    Next x

    CountStr = temp
    End Function


    Any ideas of why this is throwing an error, I'm sure its something simple. Any help would be nice.

    Thanks

    Tom

  2. #2
    Forum Expert dominicb's Avatar
    Join Date
    01-25-2005
    Location
    Lancashire, England
    MS-Off Ver
    MS Office 2000, 2003, 2007 & 2016 365
    Posts
    4,867

    Smile

    Good afternoon Tomski

    The problem is in your End If line. Take it out and your function will work fine.

    You function could phrase your If statement like this:

    If x = Str Then
    temp = temp + 1
    End If

    or like this:

    If x = Str Then temp = temp + 1

    but not a combination of the two.

    Or you could use the =COUNTIF() function to get the job done

    HTH

    DominicB

  3. #3
    Registered User
    Join Date
    08-31-2005
    Posts
    48
    Nice one, Cheers for that!

    T

  4. #4
    Forum Expert dominicb's Avatar
    Join Date
    01-25-2005
    Location
    Lancashire, England
    MS-Off Ver
    MS Office 2000, 2003, 2007 & 2016 365
    Posts
    4,867

    Smile

    Hi Tomski

    You're welcome. Thanks for the feedback.

    DominicB

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1