Microsoft KB Archive/152568

= How to Return the Nth Word from a String =

Article ID: 152568

Article Last Modified on 10/10/2006

-

APPLIES TO


 * Microsoft Excel 97 Standard Edition
 * Microsoft Excel 95 Standard Edition
 * Microsoft Excel 5.0 Standard Edition
 * Microsoft Excel 98 for Macintosh

-



This article was previously published under Q152568





SUMMARY
This article contains a sample Microsoft Visual Basic for Applications function that extracts a particular word from a sentence.



MORE INFORMATION
Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.

To Create the Custom Function
Type the following in a new Visual Basic module: Function FindNthWord(WordStrg As Variant, occur) ' Declare variables where WordStrg is the string whose Nth word you ' want to extract and occur is the number of the word (or Nth word) ' you want to extract from the string. Dim y, z As Integer Dim WordSearch

y = (Len(WordStrg) - (Len(Application.Substitute(WordStrg, " ", _ "")))) / 1      ReDim WordSearch(1 To (y + 1)) z = 1 For SearchLoop = 1 To y          z = (InStr(z, WordStrg, " ")) WordSearch(SearchLoop) = Left(WordStrg, z)          WordStrg = Application.Trim(Mid(WordStrg, z + 1)) z = 1 Next SearchLoop WordSearch(y + 1) = WordStrg ' Assigns the result to the function. FindNthWord = WordSearch(occur) End Function

To Use the Custom Function
  Enter the following in a worksheet:      A1: For a comparison of Dow Jones               B1: A2: Industrial Averages and the price of this  B2: A3: stock over the same quarter, refer to the  B3: A4: next section of the worksheet. B4:  Type the following formula in cell B1:

B1: =FindNthWord(A1,2)

 With cell B1 selected, grab the fill handle and fill the formula down through cell B4.  The resulting worksheet looks like this:      A1: For a comparison of Dow Jones               B1: a      A2: Industrial Averages and the price of this   B2: Averages A3: stock over the same quarter, refer to the  B3: over A4: next section of the worksheet. B4: section 

<div class="references_section">