Delete duplicate words from document more efficiently - vba

I compare each word with other and check if that is the duplicate if yes then delete it. For 1 to 4 pages it takes at most 5 minutes.
For a document of 50 or 100 pages I need of modification or a new idea to compare and delete duplicates with less time.
Sub Delete_Duplicates()
'***********'
'By
'MBA
'***********'
Dim AD As Range
Dim F As Range
Dim i As Long
Set AD = ActiveDocument.Range
Z = AD.Words.Count
y = 1
For i = Z To 1 Step -1
y = y + 1
Set F = AD.Words(i)
On Error Resume Next
Set s = AD.Words(i - 1)
If Trim(AD.Words(i - 1)) = "," Then Set s = AD.Words(i - 2): Set c = AD.Words(i - 1)
If Err.Number > 0 Then Exit Sub
If Not F.Text = Chr(13) And UCase(Trim(F.Text)) = UCase(Trim(s.Text)) Then
F.Text = ""
If Not c Is Nothing Then c.Text = " ": Set c = Nothing
End If
If Not c Is Nothing Then Set c = Nothing
On Error Resume Next
Call ProgressBar.Progress(y / Z * 100, True) '<<-- Progress Bar
On Error GoTo 0
Next
Beep
End Sub
Before/After

Assuming that the entire document is plain text, we can assign the entire document's text and use Split to convert it into array of words.
Since it's in array, it will be faster to process through them all vs accessing the Words collection.
This is all I can think of but perhaps there's a better way to do this? Below example uses Regex to search through and replace all matched duplicate:
Option Explicit
Sub Delete_Duplicate()
Const maxWord As Long = 2 'Change this to increase the max amount of words should be used to match as a phrase.
Dim fullTxt As String
fullTxt = ActiveDocument.Range.Text
Dim txtArr() As String
txtArr = Split(fullTxt, " ")
Dim regex As RegExp
Set regex = New RegExp
regex.Global = True
regex.IgnoreCase = True
Dim outputTxt As String
outputTxt = fullTxt
Dim n As Long
Dim i As Long
For i = UBound(txtArr) To 0 Step -1
Dim matchWord As String
matchWord = vbNullString
For n = 0 To maxWord - 1
If (i - n) < 0 Then Exit For
matchWord = txtArr(i - n) & " " & matchWord
matchWord = Trim$(Replace(matchWord, vbCr, vbNullString))
regex.Pattern = matchWord & "[, ]{0,}" & matchWord
If regex.test(outputTxt) Then
outputTxt = regex.Replace(outputTxt, matchWord)
End If
Next n
Next i
Set regex = Nothing
Application.UndoRecord.StartCustomRecord "Delete Duplicates"
ActiveDocument.Range.Text = outputTxt
Application.UndoRecord.EndCustomRecord
End Sub

You might try something along the lines of:
Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Text = "\1"
.Forward = True
.Wrap = wdFindContinue
.MatchWildcards = True
.Text = "([A-Za-z0-9'’]#)[, ]#\1"
.Execute
Do While .Found = True
.Execute Replace:=wdReplaceAll
Loop
.Text = "([A-Za-z0-9'’]#[, ]#[A-Za-z0-9'’]#)[, ]#\1"
.Execute
Do While .Found = True
.Execute Replace:=wdReplaceAll
Loop
End With
End With
Application.ScreenUpdating = True
End Sub

It is only conception but try to prepare list of all words in document and replace double or triple words if existing.
Private Sub DeleteDuplicate()
Dim wholeTxt As String
Dim w As Range
Dim col As New Collection
Dim c
For Each w In ActiveDocument.Words
AddUniqueItem col, Trim(w.Text)
Next w
wholeTxt = ActiveDocument.Range.Text
For Each c In col
'add case with ","
'maybe one letter word should be forbidden, or add extra boundary
If InStr(1, wholeTxt, c & " " & c, vbBinaryCompare) <> 0 Then
'start of doc
Selection.HomeKey wdStory
'here should be all stuff to prepare replacement
'(...)
Selection.Find.Execute Findtext:=c & " " & c, ReplaceWith:=c
wholeTxt = ActiveDocument.Range.Text
End If
Next c
Set col = Nothing
End Sub
Private Sub AddUniqueItem(ByRef col As Collection, ByVal itemValAndKey As String)
Dim s As String
On Error Resume Next
s = col(itemValAndKey)
If Err.Number <> 0 Then
col.Add itemValAndKey, itemValAndKey
Err.Clear
End If
On Error GoTo 0
End Sub

Related

Word document highlight issues

Hi I am very new to VBA word programming. I am trying to use regex and word range to select a pattern of words in a word document containing 108 pages to highlight them in Yellow and Green. When I execute the VBA code the word document hangs for a minute of 2 until the code has processed the request. Please check the code below and suggest.
**extract of the word**
*QR233A(M/W)
if LRD233 xs , LRD237 xs
LRDE233 xs , LRDE237 xs
then #R233A(M/W)
\
.
*QZR233A(M/W) #R233A(M/W) .
*QAR233A(M/W)
if LRD233 xs , LRD237 xs
LRDE233 xs , LRDE237 xs
LARSUDKFTHJS s , LARSUDKFLMS s
then #R233A(M/W)
\
.
*R233A(M/W)
if R233A(M/W) a
P831 cnf , P833 cnf , L(PB-1)SETTINGAVAIL xs
LSGPBA xs
then R233A(M/W) s
P831 cn , P833 cn
**VBA Code**
Sub Reminder_Highlight()
Dim match As VBScript_RegExp_55.match
Dim matches As VBScript_RegExp_55.MatchCollection
Dim myrange As Range
Dim rng3 As Selection
Dim counter As Integer
Set myrange = ActiveDocument.Content
Set rng3 = Selection
Dim Panel_request As Boolean
Dim Reminder_latch As Boolean
With New VBScript_RegExp_55.RegExp
.Pattern = "(\*Q(A|R|RD)\S+|LRD\S+\s(xs\s+,|xs)|(\#R|\*R)\S+)"
.Global = True
Set matches = .Execute(rng3.Text)
End With
Debug.Print matches.Count
For Each match In matches
myrange.SetRange rng3.Characters(match.FirstIndex + 1).Start, rng3.Characters(match.FirstIndex + match.Length).End
If Left(match, 1) = "#" Or Mid(match, 1, 2) = "*R" Then myrange.HighlightColorIndex = wdBrightGreen Else myrange.HighlightColorIndex = wdYellow
Debug.Print matches.Item(counter) & " "; counter
counter = counter + 1
Next
Set matches = Nothing
Set rng2 = Nothing
Set rng1 = Nothing
Set rng3 = Nothing
End Sub
Try this.
Sub HighlightSpecificWords()
Dim sArr() As String
Dim rTmp As Range
Dim x As Long
sArr = Split("highlight specific words") ' your list
Options.DefaultHighlightColorIndex = wdYellow
For x = 0 To UBound(sArr)
Set rTmp = ActiveDocument.Range
With rTmp.Find
.Text = sArr(x)
.Replacement.Text = sArr(x)
.Replacement.Highlight = True
.Execute Replace:=wdReplaceAll
End With
Next
End Sub
Before:
After:

How to select a text in Word and convert it to stacked fraction with vba?

I try to select the text in Word, for example:
10/8
18/6
12/4
And with macros convert it to this type of fractions with the horizontal line:
Sub EscribeFraccion()
Dim objRango As Range
Dim objEq As OMath
Set objRango = Selection.Range
objRango.Text = "9/36"
Set objRango = Selection.OMaths.Add(objRango)
Set objEq = objRango.OMaths(1)
objEq.BuildUp
End Sub
I would like all that text to be selected and each item to be converted like this.
I have this code that what it does is ask you through a text box, the fraction:
Sub MakeFraction ()
Dim Fraction As String, Numerator As String, Denominator As String
ActiveWindow.View.ShowFieldCodes = True
With Selection
'For user input, you could use the following 2 lines to create a fraction
Fraction = InputBox ("Please input the Fraction (ex: 1/2, 5/32)")
.Collapse (wdCollapseStart)
'Alternatively, to convert a selection, use the following line
'Fraction = Trim (.Text)
Numerator = Split (Fraction, "/") (0)
Denominator = Split (Fraction, "/") (1)
.Font.Size = Round (.Font.Size) / 2
.Fields.Add Range: = Selection.Range, Type: = wdFieldEmpty, _
PreserveFormatting: = False, Text: = "EQ \ f (" & Numerator & "," & Denominator & ")"
.MoveLeft wdCharacter, 2
.Delete
.Fields.Update
End With
ActiveWindow.View.ShowFieldCodes = False
End Sub
But instead of the imput, I would like to implement this:StrFrac = Split (Selection.Text, "/")
How could I do it? I thank you very much in advance for your support. Greetings!
Try this code:
Sub EscribeFraccion()
With ActiveDocument.Range.Find 'or Selection.Range.Find
.Text = "[0-9]#/[0-9]#"
.MatchWildcards = True
Do While .Execute
.Parent.OMaths.Add(.Parent).OMaths(1).BuildUp
Loop
End With
End Sub
Edit2
Sub EscribeFraccionSel()
With Selection.Range.Find
.Text = "[0-9]#/[0-9]#"
.MatchWildcards = True
Do While .Execute
.Parent.Text = InputBox("Please input the Fraction (ex: 1/2, 5/32)", "Input the Fraction", .Parent.Text)
.Parent.OMaths.Add(.Parent).OMaths(1).BuildUp
Loop
End With
End Sub
Edit3
Sub EscribeFraccionSel()
Dim inp
With Selection.Range.Find
.Text = "[0-9]#/[0-9]#"
.MatchWildcards = True
Do While .Execute
inp = Trim(InputBox("Please input the Fraction (ex: 1/2, 5/32)", "Input the Fraction", .Parent.Text))
inp = Split(inp, "/")
If UBound(inp) = 1 Then
If IsNumeric(inp(0)) And IsNumeric(inp(1)) Then
.Parent.Text = inp(0) & "/" & inp(1)
.Parent.OMaths.Add(.Parent).OMaths(1).BuildUp
Else
MsgBox "Error in the entered fraction"
End If
Else
MsgBox "Error in the entered fraction"
End If
Loop
End With
End Sub

Word VBA: recursive word search and work count

I am trying to create a Word macro VBA to do the following:
for the active Word document
find the name “Bob” and count how many times “this is new” is associated to Bob (recursion search and count)
For example. Bob = 2, Matthew = 1, Mark = 0
Report – JP
PQR – Bob, Mark
· Some text
Report – SH
JKL – Bob, Mark
· Some text
GHI – Bob
· This is new.
· More text
Report – JM
MNO – Bob, Mark
· Some text
DEF – Bob
· This is new.
· More text
ABC – Matthew
· This is new.
· More text
Report – BB
PQR – Bob, Mark
· Some text
I believe that my attempt using this code is not correct. Any help?
sResponse = "is new"
iCount = 0
Application.ScreenUpdating = False
With Selection
.HomeKey Unit:=wdStory
With .Find
.ClearFormatting
.Text = sResponse
' Loop until Word can no longer
' find the search string and
' count each instance
Do While .Execute
iCount = iCount + 1
Selection.MoveRight
Loop
End With
MsgBox sResponse & " appears " & iCount & " times
For example:
Sub Demo()
Application.ScreenUpdating = False
Dim StrNm As String, StrOut As String, i As Long
StrOut = "Bob = 0, " & _
"Matthew = 0, " & _
"Mark = 0, "
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "<[! ]# · This is new"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
End With
Do While .Find.Execute
If .Text = "" Then Exit Do
StrNm = Split(.Text, " ")(0)
If InStr(StrOut, StrNm) > 0 Then
i = Split(Split(StrOut, StrNm & " = ")(1), ", ")(0)
StrOut = Replace(StrOut, StrNm & " = " & i, StrNm & " = " & i + 1)
Else
StrOut = StrOut & StrNm & " = " & 1 & ", "
End If
.Collapse wdCollapseEnd
Loop
End With
Application.ScreenUpdating = True
MsgBox "Frequency Report:" & StrOut
End Sub
If you've missed any names with 'This is new', the code above will simply add them to the pre-defined StrOut list.
A part of your stated original problem was that you wanted to list ALL of the names, including names that NEVER show up as lines with the phrase "This is new". So the code must build a Dictionary of names and keep track of each name and its count as all the lines are scanned. (See this site for good information on dictionaries.)
There are a couple of "gotchas" in the ultimate solution, including allowing for names with accented characters (e.g. José) and names with spaces (e.g. "Bob Smith"). So I created a special "trim" function to scan each name and make sure the string is really just the name.
Assumptions:
Lines that DO NOT begin with "Report" are the lines that have names
The words separated by commas after the dash character are the names
The list of names ends when you find the special "separator" character
Here is the example code:
Option Explicit
Sub CountPhrase()
'--- define the dash and separator characters/strings - may be special codes
Dim dash As String
Dim separator As String
Dim phrase As String
dash = "–" 'this is not a keyboard dash
separator = "·" 'this is not a keyboard period
phrase = "This is new"
Dim nameCount As Scripting.Dictionary
Set nameCount = New Scripting.Dictionary
Dim i As Long
For i = 1 To ThisDocument.Sentences.Count
'--- locate the beginning of the names lines (that DO NOT have start with "Report")
If Not (ThisDocument.Sentences(i) Like "Report*") Then
'--- pick out the names for this report
Dim dashPosition As Long
Dim separatorPosition As Long
dashPosition = InStr(1, ThisDocument.Sentences(i), dash, vbTextCompare)
separatorPosition = InStr(1, ThisDocument.Sentences(i), separator, vbTextCompare)
Dim names() As String
names = Split(Mid$(ThisDocument.Sentences(i), _
dashPosition + 1, _
separatorPosition - dashPosition), ",")
'--- now check if the phrase exists in this sentence or not
Dim phrasePosition As Long
phrasePosition = InStr(1, ThisDocument.Sentences(i), phrase, vbTextCompare)
'--- add names to the dictionary if they don't exist, and increment
' the name count if the phrase exists in this sentence
Dim name As Variant
For Each name In names
Dim thisName As String
thisName = SpecialTrim$(name)
If Len(thisName) > 0 Then
If nameCount.Exists(thisName) Then
If phrasePosition > 0 Then
nameCount(thisName) = nameCount(thisName) + 1
End If
Else
If phrasePosition > 0 Then
nameCount.Add thisName, 1
Else
nameCount.Add thisName, 0
End If
End If
End If
Next name
End If
Next i
'--- show your work
Dim popUpMsg As String
popUpMsg = "Frequency Report:"
For Each name In nameCount.Keys
popUpMsg = popUpMsg & vbCrLf & name & _
": count = " & nameCount(name)
Next name
MsgBox popUpMsg, vbInformation + vbOKOnly
End Sub
Function SpecialTrim(ByVal inString As String) As String
'--- this function can be tricky, because you have to allow
' for characters with accents and you must allow for names
' with spaces (e.g., "Bob Smith")
'--- trim from the left until the first allowable letter
Dim keepString As String
Dim thisLetter As String
Dim i As Long
For i = 1 To Len(inString)
thisLetter = Mid$(inString, i, 1)
If LetterIsAllowed(thisLetter) Then
Exit For
End If
Next i
'-- special case: if ALL of the letters are not allowed, return
' an empty string
If i = Len(inString) Then
SpecialTrim = vbNullString
Exit Function
End If
'--- now transfer allowable characters to the keeper
' we're done when we reach the first unallowable letter (or the end)
For i = i To Len(inString)
thisLetter = Mid$(inString, i, 1)
If LetterIsAllowed(thisLetter) Then
keepString = keepString & thisLetter
Else
Exit For
End If
Next i
SpecialTrim = Trim$(keepString)
End Function
Function LetterIsAllowed(ByVal inString As String) As Boolean
'--- inString is expected to be a single character
' NOTE: a space " " is allowed in the middle, so the caller must
' Trim the returned string
Const LETTERS = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" & _
"àáâãäåçèéêëìíîïðñòóôõöùúûüýÿŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝ"
Dim i As Long
For i = 1 To Len(LETTERS)
If inString = Mid$(LETTERS, i, 1) Then
LetterIsAllowed = True
Exit Function
End If
Next i
LetterIsAllowed = False
End Function

Word VBA Find Passive Voice

I have written a procedure to find passive constructions, e.g. 'was solved', 'been written', i.e. passives ending in 'ed' or 'en', but not things like 'was fruitful'. A comment is inserted for each find.
I'm almost there - but cannot fix a couple of anomalies:
It works for 'was solved.' , 'was solved .' and 'was solved ', (NB spaces in two of these) but not in 'was solved today', i.e. where there are more words after the final verb. This last error is the one I wish to fix.
It also finds the passives in 'is being completed', i.e. two auxiliary verbs together, whether spaces follow the final verb or not. This is an added bonus, apart from the fact that the find is indicated twice.
I suspect this is to do with my Is_Alpha function, which strips punctuation from the end of the main verb.
Thanks folks, any help appreciated.
Sub Passives3()
Dim P_Flag As Boolean
Dim P_Cmt As Comment
Dim P_Rng As Range
Dim P_Rng2 As String
Dim P_New As String
Dim P_Fnd As Boolean
Dim Cmt As Comment
Dim P_Range As Range
Dim P_Ctr As Long
Dim Com_plete As Integer
Dim P_Word(7) As String
P_Word(0) = "am "
P_Word(1) = "are "
P_Word(2) = "be "
P_Word(3) = "been "
P_Word(4) = "being "
P_Word(5) = "is "
P_Word(6) = "was "
P_Word(7) = "were "
For P_Ctr = LBound(P_Word) To UBound(P_Word)
Set P_Rng = ActiveDocument.Range
With P_Rng.Find
.ClearFormatting
.text = P_Word(P_Ctr)
Debug.Print .text
.MatchCase = False
.MatchWholeWord = True
While .Execute
If P_Rng.Find.Found Then
Dim P_test As Range
Set P_test = P_Rng.Duplicate
With P_test
.MoveEnd wdWord, 2
.Select
P_New = P_test
Call Is_Alpha(P_New, P_Flag)
If P_Flag = False Then
P_New = Left(P_New, Len(P_New) - 1)
End If
End With
If (Right(Trim(P_New), 2)) = "ed" _
Or (Right(Trim(P_New), 2)) = "en" Then
Set P_Cmt = P_Rng.Comments.Add(Range:=P_Rng, text:="Passive? " & P_New)
P_Cmt.Author = "Passives"
P_Cmt.Initial = "PSV "
P_Cmt.Range.Font.ColorIndex = wdGreen
End If
End If
Wend
End With
Next
End Sub
Function Is_Alpha(P_New As String, P_Flag As Boolean) As Boolean
If Asc(Right(P_New, 1)) > 64 And Asc(Right(P_New, 1)) < 90 Or _
Asc(Right(P_New, 1)) > 96 And Asc(Right(P_New, 1)) < 123 Then
P_Flag = True
Else
P_Flag = False
End If
End Function
How about:
Sub Passives()
Dim i As Long, j As Long, Cmt As Comment, P_Words, X_Words
P_Words = Array("am ", "are ", "be ", "been ", "being ", "is ", "was ", "were ")
X_Words = Array("am ", "are ", "being ", "is ", "was ", "were ", "has ", "have ")
For i = LBound(P_Words) To UBound(P_Words)
With ActiveDocument.Range
With .Find
.ClearFormatting
.Text = "<" & P_Words(i) & "[! ]#e[dn]>"
.MatchWildcards = True
End With
Do While .Find.Execute
For j = LBound(X_Words) To UBound(X_Words)
If .Words.First.Previous.Words.First.Text = X_Words(j) Then
.Start = .Words.First.Previous.Words.First.Start
End If
Next
Set Cmt = .Comments.Add(Range:=.Duplicate, Text:="Passive?")
With Cmt
.Author = "Passives"
.Initial = "PSV "
.Range.Font.ColorIndex = wdGreen
End With
.Collapse wdCollapseEnd
Loop
End With
Next
End Sub

Header 2 text does not match the exact same text in excel : VBA

I am creating a project that lets the user create a task list within excel and then compares the user created tasks-text to the second header-text, (Header 2) within a pre-made word document. I am able to get the second header text and save it to an array, and then get the user task list and save that within an array. I then try and see if the task text that is within the Program (The second headers) are within the user task list using the function
If IsError(Application.Match(ProgArray(x), TaskArray, 0)) Then
'Find within word document and highlight red
End if
The problem I am getting is that this always returns with an error because for some reason, even though the built in watch screen debugger says otherwise, the text within the word document does not equal the exact same text within the excel sheet.
At first I used a comparing text software to determine that the header's text from word might have actually copied an extra line.
Picture of explanation:
But then I tried to trim, and check for whether or not the header text had vbNewLine
If Right$(StrFound, 2) = vbCrLf Or Right$(StrFound, 2) = vbNewLine Then
Also to no avail, as this if statement was never triggered.
My question is, is taking text from a word document also pulling some hidden value that I am just missing, and if so is there any way around this? Thank you and sorry for the wall of text.
Lastly here is my complete code: (Its not pretty as I am just going for functionality right now)
'Sub CheckHeader()
Dim blnFound As Boolean
Dim StrFound As String
Dim x As Integer, y As Integer, z As Integer
Dim TaskTotal As Integer
Dim ProgArray(149) As String
Dim TaskArray() As String
Dim NotInArray() As String
Dim NotInProg() As String
Dim appWd As Object
Dim TaskSheet As Worksheet
Set appWd = GetObject(, "Word.Application")
Set wdFind = appWd.Selection.Find
Set TaskSheet = Sheets("Task List")
'Get Task List from Excel
TaskTotal = TaskSheet.Cells(TaskSheet.Rows.Count, 1).End(xlUp).Row - 1
ReDim TaskArray(TaskTotal) As String
ReDim NotInProg(TaskTotal) As String
ReDim NotInArray(TaskTotal) As String
'Get User task list into an array to compare - 0 to 0 is for testing
For x = 0 To 0 'TaskTotal - 1
TaskArray(x) = TaskSheet.Cells(2 + x, 5).Value '+ " (" & TaskSheet.Cells(2 + x, 1).Value + " " _
& TaskSheet.Cells(2 + x, 3).Value + ": " & TaskSheet.Cells(2 + x, 4).Value + ")"
Next x
x = 0
y = 0
'Find all instances of Headings
With ActiveDocument.Range.Find
'.Text = "Test"
.Style = "Heading 2"
Do
blnFound = .Execute
If blnFound Then
'MsgBox .Parent.Text
StrFound = .Parent.Text
'StrFound = Right(StrFound, InStr(StrFound, ")") + 1)
StrFound = CStr(StrFound)
TaskSheet.Cells(2 + x, 120).Value = StrFound
'At first I thought it was also saving a new line but I couldn't get rid of it
If Right$(StrFound, 2) = vbCrLf Or Right$(StrFound, 2) = vbNewLine Then
z = 1
End If
ProgArray(x) = TaskSheet.Cells(2 + x, 120)
'StrFound
x = x + 1
Else
Exit Do
End If
Loop
End With
'Compare if List is in Program
For x = 0 To 149
If x < TaskTotal - 1 Then
If IsError(Application.Match(TaskArray(x), ProgArray, 0)) Then
NotInProg(y) = TaskArray(x)
y = y + 1
End If
End If
'If the header is not within the user created task list then run this case
If IsError(Application.Match(ProgArray(x), TaskArray, 0)) Then
'used for debugging, for some reason the header text is larger than the user text
MsgBox StrComp(ProgArray(x), TaskArray(x))
NotInArray(z) = ProgArray(x)
SearchName = NotInArray(z)
'Increase element
z = z + 1
'Check Program and highlight to show that what is in the program is not in the user task list
With wdFind
.Text = SearchName
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Execute
End With
If wdFind.Found Then
'MsgBox " Found it"
appWd.Selection.Range.HighlightColorIndex = wdRed
Else
MsgBox ProgArray(x) + " is not in TaskList"
End If
Else
'Otherwise it is in the program and if it was red, unhighlight the text
SearchName = TaskArray(x)
With wdFind
.Text = SearchName
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Execute
End With
If wdFind.Found Then
'MsgBox " Found it"
appWd.Selection.Range.HighlightColorIndex = wdNoHighlight
' For not in task Selection.Range.HighlightColorIndex = wdRed
' For not in prog Selection.Range.HighlightColorIndex = wdYellow
Else
MsgBox TaskArray(x) + " is not here"
End If
End If
'Lastly Check for Ordering
Next x
End Sub'
There are two problems within your code and solutions to them are as follows:
To cut new paragraph mark we need to cut it of in this way:
.Parent.SetRange .Parent.Start, .Parent.End - 1
Which you need to put just before:
StrFound = .Parent.Text
Additionally, add .Parent.MoveEnd right after x=x+1 inside your do...loop.