multiple conditions in a vba do while loop - vba

I have a report that can be any where from 5 to hundreds of pages that provides patient information based upon lab tests. Each patient record is separated by underscores with a check box at the end. "___________|____|" Example:
LastName,First Patient Number Unit ANC 02 #### 2/23/2017 15:56
BLOOD
GLU-ANC 416 mg/dL H* REf. RAnge: 60-100 Critical 50-399
COMMENTS: Patient detail information and notes from the doctor show up
here and can be very flexible...
More clinical info etc.
_________________________________________________________________________|____|
LastName,First Patient Number Unit CH 1234 2/23/2017 15:56
SERUM
TROP I 54 mg/dL H* REf. RAnge: 60-100 Critical 50-399
COMMENTS: Patient detail information and notes from the doctor show up
here and can be very flexible...
More clinical info etc.
_________________________________________________________________________|____|
LastName,First Patient Number Unit ANC 1234 2/23/2017 15:56
FECES
FIT POSITIVE H* REf. RAnge: "NEG"-""60-100 Critical: REPORT
COMMENTS: Patient detail information and notes from the doctor show up
here and can be very flexible...
More clinical info etc.
_________________________________________________________________________|____|
If I find certain value, for example ANC or FIT in the patient record, I can skip these records when I review the printed report. So I want to replace the underscore check box with |SKIP|.
I can do this easily with a for next loop but the problem is I don't every know how many "ARTERIAL BLOOD" or "ANC" or "FECES FIT" that will show up on a given report. So I have been trying to figure out how to replace my For Next loop with a Do While Selection.Find.Execute = True statement.
But have tried many variations and cannot get the syntax right.
Any help would be greatly appreciated!
Here is my working For Next Loop
Sub xSimplefind()
Dim vtext As String
vtext = InputBox("Text to find") 'Here I enter 1st search value ie. "ANC"
For i = 1 To 7
With Selection.Find
.Execute FindText:=vtext
Selection.MoveRight Unit:=wdCharacter, Count:=1
End With
'Once I find that first item, I then look for the very next "|_____|"
With Selection.Find
.Execute FindText:="|____|" 'TypeText overwrites Selected text.
Selection.TypeText Text:="|SKIP|"
End With
Next i
End Sub

This isn't exactly what you need, but an example will hopefully set you on the right track:
Option Explicit
Sub MultiFind()
Dim valueToSkip() As String
valueToSkip = Split("ANC,FIT,ARTERIAL BLOOD,FECES FIT", Delimiter:=",")
Dim found As Boolean
Dim value As Variant
Dim result As Variant
found = False
For Each value In valueToSkip
With Selection.Find
Set result = .Execute(FindText:=value)
If Not result Is Nothing Then
found = True
Exit For
End If
End With
Next value
If found Then
'--- add |SKIP| here
End If
End Sub

This code works if anyone else needs to do something like this...
Thanks for the input and help from others!!
= = = = = Solution Found = = = = = = = = =
Sub test()
Dim vtext As Variant
For Each vtext In Array("Arterial", "ANC", "FIT", "PREVIOUS")
Selection.HomeKey Unit:=wdStory
'
'Inner loop to check every line
'
While True
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = vtext
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
With Selection.Find
.Text = "|"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.MoveRight Unit:=wdCharacter, Count:=5, Extend:=wdExtend
If Selection.Text <> "|SKIP|" Then
Selection.Text = "|SKIP|"
Else
GoTo DoNextWord
End If
Wend
DoNextWord:
Next vtext
End Sub

Related

VBA Word, Remove Specific Highlighting Color "Red" get stuck some times at infinite loop

I want to delete the red highlighting color from the MS Word document.
Explanation:
I made a module in MS Word documents that search/find any text highlighting with red color - a text marked with red from the tool shown in the image below. The following code is either working fine or make the MS Word stop responding. I'm not sure why it gets crashing, but I guess due to the loop that I am using. I wish there is something like: .Replacement.HighlightColorIndex = wdred ; and then .Execute Replace:=wdReplaceAll ; instead of the loop.
The VBA code that I wrote:
Sub RemoveSpecificHighlightingColor()
'
' Remove Specific Highlighting Color Macro
' This Macro go through the document and search for any Red color highlighting word and remove it
' colors code: https://learn.microsoft.com/en-us/office/vba/api/word.wdcolorindex
'
Selection.GoTo wdGoToPage, wdGoToAbsolute, 1 'Start at the top of the document
Selection.Find.ClearFormatting
Selection.Find.Highlight = True
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop 'stop at the end of the document
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While (.Execute(Forward:=True) = True) = True
DoEvents 'keeps Word responsive
If Selection.Range.HighlightColorIndex = wdRed Then
Selection.Range.Delete
End If
Loop
MsgBox "Done!" ' just for testing
End With
End Sub
Some explanation about the code:
I noticed if I select at the middle of the document then run the code, the code start from the mouse selection not from the top. This is why I mentioned the first statement.
Some of the code I got from the record marco feature and from help online. The record marco detect all highlighting color not specific color.
I used Selection.Find so I selected .Wrap = wdFindStop
There is no difference if I keep or remove Format, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, and MatchAllWordForms.
The main issue is the While loop or any loop that I am using. The one shown in the code check for all highlighting colors and if the color is red, then remove it, otherwise check for another.
Any help is appreciated, thanks!
The big problem with your code is that you are using the Selection object. When you select things in your code the screen has to be redrawn with each change of selection. As Selection.Find selects every match it finds that is a lot of redrawing.
In this instance you can avoid using Selection by using a Range object instead (ActiveDocument.Content is a range). When you use .Find with a range the range is redefined each time a match is found, enabling you to change the properties of that range.
Sub RemoveSpecificHighlightingColor()
Application.ScreenUpdating = False
With ActiveDocument.Content
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Highlight = True
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop 'stop at the end of the document
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Do While .Find.Execute = True
If .HighlightColorIndex = wdRed Then .Delete
Loop
End With
Application.ScreenUpdating = True
End Sub
For example:
Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Replacement.Text = ""
.Format = True
.Forward = True
.Highlight = True
.Wrap = wdFindStop
End With
Do While .Find.Execute
If .HighlightColorIndex = wdRed Then .Delete
'The next If ... End If block is needed if the highlighted content could be in a table
If .Information(wdWithInTable) = True Then
If .End = .Cells(1).Range.End - 1 Then
.End = .Cells(1).Range.End
.Collapse wdCollapseEnd
If .Information(wdAtEndOfRowMarker) = True Then
.End = .End + 1
End If
End If
End If
'The next line is needed if the highlighted content could include the final paragraph break
If .End = ActiveDocument.Range.End Then Exit Do
.Collapse wdCollapseEnd
Loop
End With
Application.ScreenUpdating = True
End Sub
Do note that there's a bug in Word's Find which means it won't find anything if the document consists of a single highlighted paragraph. Additionally, I haven't included code to test whether a found range spans some text as well as part of a field or spans two or more highlight colours. Consequently, neither condition will be processed.
I tried to trace the issue. What I noticed is, in some documents only (mixed of .doc and .docx file type), once I run the code, it goes through the document pages and finds and deletes the red highlighting color, that once all are replaced, the MS Word stuck. Once the MS Word got stuck, the cursor is changing rapidly, as if the screen has to be redrawn, and after a few seconds the program stops responding, and even if I wait for a while it will be stuck until I force to close the MS Word. This happened with or without red highlighting color in the document.
Explanation of the code:
The code runs each page alone by making the code start from the first page and count the number of pages. Then go through each page and select the text.
Apply the filtering code and deleting for the specific selection only, then check for a new page.
I treated the pause/stuck as a bouncing button without a pull-up or pull-down resistor i.e., once the physical button is pressed it fluctuate before it reaches a steady state.
Iteration...
The final code that I used, and It's now working for all documents is shown below:
Sub RemoveSpecificHighlightingColor()
'
' Remove Specific Highlighting Color Macro
' This Macro go through the document and search for any Red color highlighting word and remove it
' colors code: https://learn.microsoft.com/en-us/office/vba/api/word.wdcolorindex
'
Dim NumberOfAllPages As Integer
' Dim LastPageNumber As Integer
Dim PageNumber As Integer
Dim TempCounter As Integer
Dim TemoEnd As Long
Selection.Find.ClearFormatting
PageNumber = 1 'Starting page
NumberOfAllPages = ActiveDocument.ActiveWindow.Panes(1).Pages.Count
' LastPageNumber = 3 'Last page to reach - for testing
Selection.GoTo wdGoToPage, wdGoToAbsolute, PageNumber 'GoTo Page PageNumber
' Debug.Print "Start"
While PageNumber - 1 < NumberOfAllPages 'LastPageNumber
DoEvents 'keeps document responsive
Selection.GoTo wdGoToPage, wdGoToAbsolute, PageNumber 'GoTo Page PageNumber
Selection.Bookmarks("\Page").Select 'Select all the text in the page
With Selection.Find
.Highlight = True
.Text = ""
.Replacement.Text = ""
.Forward = True
Do While (.Execute(Forward:=True) = True) = True
DoEvents 'keeps document responsive
If Selection.Range.HighlightColorIndex = wdRed Then Selection.Range.Delete
' If the process is stuck at the same location for while then (50 times) it mean the page is full check from Red Highlighting Color
If ActiveWindow.Selection.End = TemoEnd Then
TempCounter = TempCounter + 1
End If
If TempCounter > 50 Then Exit Do
' Debug.Print ActiveDocument.Range.End
' Debug.Print ActiveWindow.Selection.End
TemoEnd = ActiveWindow.Selection.End
Loop
End With
TempCounter = 0 ' reset counter
' Debug.Print PageNumber
PageNumber = PageNumber + 1
Wend
End Sub
I can't tell you where your error is, but here's a working code
Sub UNHIGHCOLOR()
'HOW MANY HIGHLIGHT REGIONS ARE - store to AAAM
Selection.HomeKey wdStory
'HIG_COUNT Macro
'CTRL-FN-SHIFT TO BREAK
START:
'Selection.HomeKey wdStory
Selection.Find.ClearFormatting
Selection.Find.Highlight = True
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
If .Found Then
'MsgBox "found"
If Selection.Range.HighlightColorIndex = wdRed Then
'MsgBox "RED"
'Selection.Range.HighlightColorIndex = 0
End If
AAAM = AAAM + 1
GoTo START
Else
'MsgBox "not found"
'MsgBox AAAM & " HIGH REGIONS"
End If
End With
Selection.HomeKey wdStory
'*********************************************************
'FOR AAAM REGIONS CHANGE HIGHLIGHT RED COLORS TO NO COLOR
For X = 1 To AAAM + 1
'UNHIGHCOLOR_RED_NEXT
Selection.Find.ClearFormatting
Selection.Find.Highlight = True
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
If Selection.Range.HighlightColorIndex = wdRed Then
'MsgBox "RED"
Selection.Range.HighlightColorIndex = 0 'NO COLOR
End If
Selection.Collapse (wdCollapseEnd) 'TO FIND NEXT
Next
End Sub

How to convert a letter to superscript in macro (Word)?

I want change a word to superscript in macro.
word 2016.
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "7th of every month."
.Replacement.Text = "7^th of every month."
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchAllWordForms = False
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
when i run the macro instead of making "th" as supercript it just create space between "7" and "h"
Result is like this "The meeting is on 7 h of every month."enter image description here
The following code searches for one or two digits, immediately followed by th and superscripts the th. This makes it more flexible than searching the specific string.
It works with a Range rather than a Selection object which will make it faster. The search type is a "wildcard" search.
Sub SuperScript_th_()
Dim rngFind As Word.Range
Dim searchText As String
Dim found As Boolean
Set rngFind = ActiveDocument.content
searchText = "[0-9]{1;2}th"
'searchText = "7th"
With rngFind.Find
.Text = searchText
.MatchWildcards = True
.wrap = wdFindStop
found = .Execute
Do While found
rngFind.Collapse wdCollapseEnd
rngFind.MoveStart wdCharacter, -2
rngFind.Font.Superscript = True
rngFind.End = ActiveDocument.content.End
found = .Execute
Loop
End With
End Sub
The ^t is the instruction in Word's Find to insert a TAB (like pressing the Tab-key on the keyboard). That's why the code in the quesiton is inserting space between the 7 the h in the Replacement.Text.
While Word's Find/Replace is able to format text as part of the Replacement, the difficulty here is that
Not all the text being found should be formatted
The entire text needs to be retained
It's not possible to tell Find/Replace to find text, then format only part of it. That's why the Find needs to be separate from the formatting action. If the entire found text needed to be formatted, then Find/Replace alone would work.
There are also no commands in Word's Find/Replace to apply formatting as a "code" in the Replacement.Text string.
Why don't simply try like this
With Selection.Find
.Text = "7th of every month."
'.Replacement.Text = "7^th of every month."
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchAllWordForms = False
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
Do While .Execute
ActiveDocument.Range(Selection.Range.Start + 1, Selection.Range.Start + 3).Font.Superscript = True
Loop
End With
Edit: With turning off some word options etc the 8 sec time to process 60 pages and 1240 replacement may be reduced to around 2 seconds. the test code
Sub test2()
Dim Rng As Range, tm As Double
tm = Timer
TurnOnOff False
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "7th of every month."
X = 0
Do While .Execute
ActiveDocument.Range(Selection.Range.Start + 1, Selection.Range.Start + 3).Font.Superscript = True
X = X + 1
Loop
End With
Debug.Print X, Timer - tm
TurnOnOff True
End Sub
Sub TurnOnOff(OnOff As Boolean)
Application.ScreenUpdating = OnOff
With Options
.Pagination = OnOff
.CheckSpellingAsYouType = OnOff
.CheckGrammarAsYouType = OnOff
End With
End Sub

How to detect numbering in simple vba string replacement

I'm trying to replace numbering (Word's 1. , 2. , etc.). In a simple string and replace search but I can't seem to find the numbers.
This is for Word 365, and I'm using the VB editor in there.
Sub ayaya()
Documents.Open FileName:=ActiveDocument.Path + "\Doc1.docm"
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "SSS"
.Replacement.Text = "PPP"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
With Selection
If .Find.Forward = True Then
.Collapse Direction:=wdCollapseStart
Else
.Collapse Direction:=wdCollapseEnd
End If
.Find.Execute Replace:=wdReplaceAll
End With
End Sub
My word document looked like this:
SSS
SSS
1. SSS
and turned to
PPP
PPP
1. PPP
but when I replace the search to any variation of
With Selection.Find
.Text = "1. SSS"
It does not find the text.
You are not finding the number associated with the paragraph text because it most likely is a ListLevelNumber and these are automatically generated by the ListFormat style. In other words, they are not part of the physical text that can be found using a Search, at least the way you currently have it setup in your code.
A separate Search would be required to find the ListParagraph Style being used and then some additional code that would manipulate the ListLevelNumber if that is what you are attempting to do.
Below is example code that determines what the ListLevelNumber is on a given paragraph and then takes some action based on what the level actually is:
Sub IsSelectionListParagraph()
Dim i As Integer
If Selection.Range.ListParagraphs.Count > 0 Then
For i = 1 To Selection.Range.ListParagraphs.Count
Select Case Selection.Range.ListParagraphs(i).Range.ListFormat.ListLevelNumber
Case Is = 1
Debug.Print Selection.Range.Text
Case Is = 2
Debug.Print Selection.Range.Text
Case Else
Debug.Print Selection.Range.Text
End Select
Next
End If
End Sub
Numbering is a ListParagraphs Object and can't be searched as if it's plain text.

Delete a paragraph that starts with specific word from selection

I want to delete a paragraph that starts with string "Page:" from the selection
Here is the sample text that I have:
Page: 28
Page: 44 contains a lot of example. But look up here for the detailed
explanation. This may go for more than one, two or three lines. This
totally depends upon the length of the text
Date: 10 Jan 2018
Some text goes here with Page: 108
I’ve some more text here
Few more
Final Text
Page: 208
This is the end
The code I have so far:
Sub DelPara()
Dim para As Paragraph
With Selection.Range.Find
.ClearFormatting
.Text = "[^13^11]Page:"
.Forward = True
.MatchWildcards = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
If (Selection.Range.Find = True) Then
para.Range.Delete
End If
End With
End Sub
The output should be
Date: 10 Jan 2018
Some text goes here with Page: 108
I’ve some more text here
Few more
Final Text
This is the end
The code below will search all instances of the search term in the current selection and delete the search term plus the entire paragraph in which the end of the term is located.
The key to this is using two Range objects: one for the original Range to be searched (the selection), the other for the actual search. In this way, the range that performs the actual search can be extended from the end of the last successful search to the end of the original range.
Sub DelPara()
Dim rngFind As Word.Range, rngSel As Word.Range
Dim para As Paragraph
Dim bFound As Boolean
Set rngSel = Selection.Range
Set rngFind = rngSel.Duplicate
With rngFind.Find
.ClearFormatting
.text = "[^13^11]Page:"
.Forward = True
.MatchWildcards = True
.wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
bFound = rngFind.Find.Execute
Do While bFound
rngFind.End = rngFind.paragraphs.Last.Range.End
rngFind.Delete
rngFind.Collapse wdCollapseEnd
rngFind.End = rngSel.End
bFound = rngFind.Find.Execute
Loop
End Sub
All you need is a wildcard Find/Replace with:
Find = ^13Page:[!^13]{1,}
Replace = nothing
No code required. At most, you might need to insert an empty paragraph at the beginning of the document and delete it afterwards - but then only if the first para starts with 'Page:'. Nevertheless, as a macro:
Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
.InsertBefore vbCr
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "^13Page:[!^13]{1,}"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
.Characters.First = vbNullString
End With
Application.ScreenUpdating = True
End Sub
If you want to process only the selected range, change 'ActiveDocument' to 'Selection'.

Word 2016 VBA loop until end of document

I've looked at many different answers online but have not been able to find a solution that fits my code. This is my first time writing VBA in Word (have some moderate experience in Excel).
I thought this post might be what I need but it doesn't stop the loop at the end of the document for me.
I'm trying to insert a continuous section break before the start of a new section, which I designate as text that is formatted with style Heading 1. I'm totally open to doing this another way and would be grateful for your insights!
Sub InsertSectionBreak()
' Go to start of document
Selection.HomeKey Unit:=wdStory
' Find next section based on header formatting, insert continuous section break just before
'
Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles("Heading 1")
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Do While Selection.Find.Execute = True
Selection.Find.Execute
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.InsertBreak Type:=wdSectionBreakContinuous
Loop
End Sub
The code in the question is not bad, but has a major problem: The Selection is being moved towards the front of the document in order to insert the Section Break. This means that next time Find runs it again finds the same Heading 1 and thus repeatedly inserts Section Breaks in the same place.
The other problem is that the code is executing Find as part of the Do While criterium (which is why it's not finding the first instance of Heading 1 in the document).
The following code sample works with Range objects instead of the Selection. You can think of a Range like an invisible selection with a very important difference: there can be multiple Ranges; there can be only one selection.
The suggested code uses two ranges: one for the Find and the other for inserting the Section Break. The Find range is set to the entire document. Whether the Find is successful is stored in a boolean variable (bFound).
If Find is successful the found range is duplicated to the range for the Section break. Duplicate makes an independent "copy" of the original range so that they can be manipulated independently of one another. The range for the section break is then collapsed to its starting point (think of it like pressing left-arrow), then the section break is inserted.
The Find range, however, is collapsed to its end point in order to move it beyond the text formatted with Heading 1 so that the next Heading 1 can be targeted. Find is then executed again and the loop repeats until no more instances of Heading 1 are found.
Sub InsertSectionBreak()
Dim rngFind As Word.Range, rngSection As Word.Range
Dim bFound As Boolean
Set rngFind = ActiveDocument.content
' Find next section based on header formatting, insert continuous section break just before
'
rngFind.Find.ClearFormatting
rngFind.Find.style = ActiveDocument.styles("Heading 1")
With rngFind.Find
.text = ""
.Replacement.text = ""
.Forward = True
.wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
bFound = .Execute
End With
Do While bFound
Set rngSection = rngFind.Duplicate
rngSection.Collapse wdCollapseStart
rngSection.InsertBreak Type:=wdSectionBreakContinuous
rngFind.Collapse wdCollapseEnd
bFound = rngFind.Find.Execute
Loop
End Sub
If the content you're interested is related to a heading, you can obtain all the content under that heading without the need for Section breaks. For example:
Sub GetHeadingSpanText()
Application.ScreenUpdating = False
Dim Rng As Range
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = InputBox("What is the text to find?")
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
If .Find.Found = True Then
Set Rng = .Paragraphs(1).Range
Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
MsgBox Rng.Text
End If
End With
Set Rng = Nothing
Application.ScreenUpdating = True
End Sub
Note that this approach get's all the content associated with the nearest heading, regardless of its level; a more sophisticated approach can be use to get all the content associated with a particular heading level so that, if the match is found under a sub-heading, the prior major heading is used to determine the range spanned.