Friday, March 12, 2010

a VBA function counting chars

It may happen to find in some data sources more than one occurence of a data type inside the same field, separated by a special char.
But in many cases that  char may be not so special and be misguiding when trasposing the field.
Let's take as example Thomson SDC database, where in the alliance name you find the alliance participants names separated by the / char.
Obviously the / char may also be integral part of some participant name; so we need to count the occurrence of the / char in order to compare it to the number of partipants indicated in the same record in order to do futher cleaning, if needed.

So I wrote a small DBA function called CHARCOUNT, and I'm posting it here

Function charcount(inputstring As String, findstring As String)
' return the number of occurrences of findstring in inputstring

Dim a$, b$
Dim c, i As Integer

a$ = inputstring
b$ = findstring

c = 0
For i = 1 To Len(a$) - Len(b$) + 1
    If Mid(a$, i, Len(b$)) = b$ Then
        c = c + 1
    End If
Next

charcount = c

End Function
Function charcount(inputstring As String, findstring As String)
' return the number of occurrences of findstring in inputstring

Dim a$, b$
Dim c, i As Integer

a$ = inputstring
b$ = findstring

c = 0
For i = 1 To Len(a$) - Len(b$) + 1
    If Mid(a$, i, Len(b$)) = b$ Then
        c = c + 1
    End If
Next

charcount = c

End Function

No comments:

Post a Comment