Counting Spaces (1 Viewer)

crosmill

Registered User.
Local time
Today, 20:37
Joined
Sep 20, 2001
Messages
285
I need to be able to count the number of spaces in each record.

Any ideas.

Cheers
 

Mile-O

Back once again...
Local time
Today, 20:37
Joined
Dec 10, 2002
Messages
11,316
In each record or a specific field in each record?
 

crosmill

Registered User.
Local time
Today, 20:37
Joined
Sep 20, 2001
Messages
285
a specific field in each record
 

Mile-O

Back once again...
Local time
Today, 20:37
Joined
Dec 10, 2002
Messages
11,316
Put this in a module:

Code:
Public Function CountSpaces(strField As String) As Integer
    On Error Goto Err_CountSpaces
    Dim intCounter As Integer
    For intCounter = 1 To Len(strField)
        If Mid(strField, intCounter, 1) = " " Then
            CountSpaces = CountSpaces + 1
        End If
    Next intCounter
Exit_CountSpaces:
    Exit Function
Err_CountSpaces:
    CountSpaces = 0
    Resume Exit_CountSpaces    
End Function

In your query:

NewField: CountSpaces([MyField])
 
Last edited:

crosmill

Registered User.
Local time
Today, 20:37
Joined
Sep 20, 2001
Messages
285
Genius!

I never would have thought to do it like that.

Slight mistake on the penultimate line though.
I changed it to this and it works.

I tend to wing it a bit with modules though. Is my correction right?

Public Function CountSpaces(strField As String) As Integer
On Error GoTo Err_CountSpaces
Dim intCounter As Integer
For intCounter = 1 To Len(strField)
If Mid(strField, intCounter, 1) = " " Then
CountSpaces = CountSpaces + 1
End If
Next intCounter
Exit_CountSpaces:
Exit Function
Err_CountSpaces:
CountSpaces = 0
Resume Exit_CountSpaces
End Function



Cheers Mile
 

crosmill

Registered User.
Local time
Today, 20:37
Joined
Sep 20, 2001
Messages
285
It also creates #Error on a NULL string
 

Pat Hartman

Super Moderator
Staff member
Local time
Today, 15:37
Joined
Feb 19, 2002
Messages
43,484
A simpler method if you only care about leading and trailling spaces. This method won't count embedded spaces.
Len(YourField) - Len(Trim(YourField))
 

Mile-O

Back once again...
Local time
Today, 20:37
Joined
Dec 10, 2002
Messages
11,316
NewField: IIf(IsNull([MyField]), 0, CountSpaces([MyField]))
 

crosmill

Registered User.
Local time
Today, 20:37
Joined
Sep 20, 2001
Messages
285
Brilliant!

Works a treat.

For curiousities sake, can you deal with the NULL in the Module. I couldn't get it to work?
 

Users who are viewing this thread

Top Bottom