Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Count Until Selected Word

Status
Not open for further replies.

ThereUare

Programmer
Oct 16, 2007
16
US
I need some code for a word doc to count the number of words until the selected word.

In other words, I need to find the word count position of a particular word.

Any loops or maybe a property example would really be helpful.

Thanks
 


Hi, ThereUare (Programmer)

How about posting the code that you have generated so far.

Skip,

[glasses]Just traded in my old subtlety...
for a NUANCE![tongue]
 
Something like this should get you started:

Code:
[blue]Sub CountWords()
Dim R As Range
Dim W As String
W = InputBox("Please enter word to count until:")
If W <> "" Then
    Set R = Selection.Range
    R.Collapse wdCollapseEnd
    If R.Find.Execute(W) Then
        R.Start = Selection.End
        MsgBox "There are " & R.Words.Count & _
               " words between the current selection and """ _
               & W & """"
        Else
        MsgBox """" & W & """ not found."
    End If
End Sub[/blue]

Enjoy,
Tony

------------------------------------------------------------------------------------
We want to help you; help us to do it by reading this: Before you ask a question.

I'm working (slowly) on my own website
 
Thanks Tony, that was very helpful. My only concern is that I will have a problem if that word is repeated in the document. It looks like it will go to the first instance and that will be the end. Is there a way I can get the word count specifically for the instance of the selected word?
 
1. You mention "selected word". Assuming you do NOT want to include the word at the selection:
Code:
Sub CountToHere()
Dim r As Range
Set r = Selection.Range
With r
   .Expand Unit:=wdWord
   .Collapse 1
   .Start = ActiveDocument.Range.Start
End With
MsgBox r.ComputeStatistics(wdStatisticWords)
End Sub

2. Also assumes you want the count from the start of the document (although you do not actually state that).

The code above do not require you actually select the whole word. You can simply have the Selection (cursor) in a word.

Gerry
 
Thanks fumei, that was exactly what I was looking for.
Seems so simple now that I look at it.
 
1. I am always curious when people ask about using VBA for such things.

Why do you want a VBA "solution"? You could just as easily go: Shift-Ctrl-Home and then use Tools > Word Count

That would give the word count for the Selection (from the cursor to Home, or the start of the document).

2. Why do you even need to know this? As I said, I am simply curious.

Gerry
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top