#1   Report Post  
Posted to microsoft.public.excel.programming
external usenet poster
 
Posts: 25
Default counting

Is there a better way to count the number of words in a string than:

intWords = 1
For i = 1 To Len(strIssuerName)
If Mid(strIssuerName, i, 1) = " " Then intWords = intWords + 1
Next i

? This obviously isn't perfect since if there were two spaces in a row it
would count an extra word...

Also, is there an easy way to pick off the last two words in a string? I'm
currently using ExtractElement from one of J Walkenbach's books.

Thanks.
Dave


  #2   Report Post  
Posted to microsoft.public.excel.programming
external usenet poster
 
Posts: 7,247
Default counting

Dave,

Try the following:

Sub CountWords()
Dim S As String
Dim V As Variant
Dim N As Long
S = " this is a test"
S = Application.Trim(S)
V = Split(S, " ")
N = UBound(V) - LBound(V) + 1
Debug.Print "there are " & N & " words"
End Sub

For the last and next to last words, use
LastWord = V(UBound(V))
NextToLastWord = V(UBound(V) - 1)


--
Cordially,
Chip Pearson
Microsoft MVP - Excel
Pearson Software Consulting, LLC
www.cpearson.com




"Dave B" wrote in message
...
Is there a better way to count the number of words in a string than:

intWords = 1
For i = 1 To Len(strIssuerName)
If Mid(strIssuerName, i, 1) = " " Then intWords = intWords + 1
Next i

? This obviously isn't perfect since if there were two spaces in a row it
would count an extra word...

Also, is there an easy way to pick off the last two words in a string?

I'm
currently using ExtractElement from one of J Walkenbach's books.

Thanks.
Dave




Reply
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules

Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
counting function but not double counting duplicates JRD Excel Worksheet Functions 2 November 7th 07 06:43 PM
Counting John Excel Discussion (Misc queries) 3 August 15th 07 06:20 PM
Counting Voodoodan Excel Discussion (Misc queries) 11 March 23rd 06 09:34 PM
Counting rows, then counting values. Michael via OfficeKB.com Excel Discussion (Misc queries) 7 August 4th 05 10:57 PM
Counting names in a column but counting duplicate names once TBoe Excel Discussion (Misc queries) 9 May 11th 05 11:24 PM


All times are GMT +1. The time now is 09:04 AM.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Copyright ©2004-2024 ExcelBanter.
The comments are property of their posters.
 

About Us

"It's about Microsoft Excel"