Finding rest of sentence after finding an specific word - excel

I have created a code that searches different words in a column in a word document.
After finding the word, the code returns the value "yes" to the excel.
I want the code to extract the rest of the sentence after finding the word that I´m looking for.
The rest of the sentences are always something like:
Update system format.
Search for other inputs.
Havent found the sentence that it needs to do.
In conclusion, they are always a small sentence and a new paragraph after.
The code that I have developed is the following:
Sub findSubprocesos()
Dim wrdApp As New Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = CreateObject("Word.Application")
Dim FindWord As String
Dim List As String
Dim Dict As Object
Dim NextFormula As Range
Dim RefElem As Range
Dim Key
Dim Wbk As Workbook: Set Wbk = ThisWorkbook
Set Dict = CreateObject("Scripting.Dictionary")
Set NextFormula = Worksheets("Datos2").Range("V2:V5")
With Dict
For Each RefElem In NextFormula
If Not .Exists(RefElem) And Not IsEmpty(RefElem) Then
Sheets("Datos2").Range("R3").Value = RefElem.Value
Debug.Print RefElem
FindSubs
On Error GoTo Skip
End If
Next RefElem
Skip:
End With
End Sub
Private Sub FindSubs()
Dim wrdApp As New Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = CreateObject("Word.Application")
Dim FindWord As String
Dim List As String
Dim Dict As Object
Dim NextFormula As Range
Dim RefElem As Range
Dim Key
Dim Wbk As Workbook: Set Wbk = ThisWorkbook
Range("U3:U50").ClearContents
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("C:\Users\rriveragarrido\Desktop\Proyectos\Proyecto solaris (endesa) (PROPIO)\prueba macros\ZZZ\Narrativas antiguas\1059\1059_NAR_OTC.RC.03.01_CC.END.GEN_ENG_31.12.20.docx", OpenAndRepair:=True)
Dim cell As Range
Dim bIsEmpty As Boolean
bIsEmpty = False
For n = 3 To 20
For Each cell In Worksheets("Datos").Range("S" & n)
If IsEmpty(cell) = False Then
FindWord = Wbk.Sheets("Datos2").Range("S" & n).Value 'Modify as necessary.
wrdApp.Selection.WholeStory
wrdApp.Selection.FIND.ClearFormatting
With wrdApp.Selection.FIND
.ClearFormatting
.Text = FindWord
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
If .Execute Then
Sheets("Datos2").Range("U" & n).Value = "Yes"
Else
'Sheets("Datos2").Range("T" & n).Value = "No"
wrdApp.Quit SaveChanges:=0
Sheets("Datos2").Range("U3:U50").Copy Sheets("Subprocesos").Range("A3:A50").End(xlToRight).Offset(0, 1)
GoTo Skip2
End If
End With
End If
Next cell
Next
Skip2:
End Sub
This is the part were I need to extract the rest of the sentence:
If .Execute Then
Sheets("Datos2").Range("U" & n).Value = "Yes"
Else
'Sheets("Datos2").Range("T" & n).Value = "No"
wrdApp.Quit SaveChanges:=0
Sheets("Datos2").Range("U3:U50").Copy Sheets("Subprocesos").Range("A3:A50").End(xlToRight).Offset(0, 1)
Currently is only writing "yes" when the sentence is found and pasting the information in a column and going to the next word if it is not found.

What you want to do is possible by using the Sentences collection of the document. Hopefully you can adapt the sample code below to your needs:
Option Explicit
Sub test()
Dim foundSentences As Collection
Set foundSentences = FindTheSentencesContaining(ThisWord:="access", _
FromThisDoc:="C:\Temp\test.docx")
If foundSentences Is Nothing Then
Debug.Print "The word doc was not found!"
Else
Debug.Print "found " & foundSentences.Count & " sentences"
Dim sentence As Variant
For Each sentence In foundSentences
Debug.Print sentence
Next sentence
End If
End Sub
Function FindTheSentencesContaining(ByVal ThisWord As String, _
ByVal FromThisDoc As String) As Collection
Dim wordWasRunning As Boolean
wordWasRunning = IsMSWordRunning
Dim wordApp As Word.Application
Set wordApp = AttachToMSWordApplication
On Error Resume Next
Dim wordDoc As Word.Document
Set wordDoc = wordApp.Documents.Open(Filename:=FromThisDoc, ReadOnly:=True)
On Error GoTo 0
If wordDoc Is Nothing Then Exit Function
Dim allSentences As Collection
Set allSentences = New Collection
Dim sentence As Variant
For Each sentence In wordDoc.Sentences
sentence.Select
With wordApp.Selection
.Find.Text = ThisWord
.Find.Forward = True
.Find.Wrap = wdFindStop
.Find.MatchCase = False
If .Find.Execute Then
'--- extend the selection to include the whole sentence
.Expand Unit:=wdSentence
allSentences.Add wordApp.Selection.Text
'--- move the cursor to the end of the sentence to continue looking
.Collapse Direction:=wdCollapseEnd
.MoveEnd Unit:=wdSentence
Else
'--- didn't find it, move to the next sentence
End If
End With
Next sentence
wordDoc.Close SaveChanges:=False
If Not wordWasRunning Then
wordApp.Quit
End If
Set FindTheSentencesContaining = allSentences
End Function
In a separate module, I have the following code (pulled from my library of code to reuse):
Option Explicit
Public Function IsMSWordRunning() As Boolean
'--- quick check to see if an instance of MS Word is running
Dim msApp As Object
On Error Resume Next
Set msApp = GetObject(, "Word.Application")
If Err > 0 Then
'--- not running
IsMSWordRunning = False
Else
'--- running
IsMSWordRunning = True
End If
End Function
Public Function AttachToMSWordApplication() As Word.Application
'--- finds an existing and running instance of MS Word, or starts
' the application if one is not already running
Dim msApp As Word.Application
On Error Resume Next
Set msApp = GetObject(, "Word.Application")
If Err > 0 Then
'--- we have to start one
' an exception will be raised if the application is not installed
Set msApp = CreateObject("Word.Application")
End If
Set AttachToMSWordApplication = msApp
End Function

A simple demo outputting the content to a message box, for all found instances:
Sub Demo()
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = InputBox("What is the Text to Find")
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Do While .Find.Execute
With .Duplicate
.End = .Sentences.First.End
MsgBox .Text
End With
.Collapse wdCollapseEnd
Loop
End With
End Sub
Do be aware, though, that VBA has no idea what a grammatical sentence is. For example, consider the following:
Mr. Smith spent $1,234.56 at Dr. John's Grocery Store, to buy:
10.25kg of potatoes; 10kg of avocados; and 15.1kg of Mrs. Green's Mt. Pleasant macadamia nuts.
For you and me, that would count as one sentence; for VBA it counts as 5 sentences.

Related

Delete paragraph in Microsoft Word if Excel cell is a specified value

This is my first post here and I'm very, very new to vba.
I have an Excel worksheet that I am using to assist in drafting several Word documents. I would like to program a command in Excel that if a specific cell has a specific value, it will delete a particular paragraph in a Word document. Specifically, I want to do something like the following:
if activesheet.range("I99")="1" then
'code to delete specific paragraph in Word document
elseif activesheet.range("I99")="2" then
'code to delete different paragraph in Word document
elseif activesheet.range("I99")="3" then
'code to delete different paragraph in Word document
end if
The following generic code (which I found on this site) in Word does what I want it to do in Word, but I can't get it to work in Excel:
Sub SomeSub()
Dim StartWord As String, EndWord As String
Dim Find1stRange As Range, FindEndRange As Range
Dim DelRange As Range, DelStartRange As Range, DelEndRange As Range
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Setting up the Ranges
Set Find1stRange = ActiveDocument.Range
Set FindEndRange = ActiveDocument.Range
Set DelRange = ActiveDocument.Range
'Set your Start and End Find words here to cleanup the script
StartWord = "From: Research.TA#traditionanalytics.com|Tradition Analytics Commentary| | |"
EndWord = "This message has been scanned for malware by Websense. www.websense.com"
'Starting the Find First Word
With Find1stRange.Find
.Text = StartWord
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
'Execute the Find
Do While .Execute
'If Found then do extra script
If .Found = True Then
'Setting the Found range to the DelStartRange
Set DelStartRange = Find1stRange
'Having these Selections during testing is benificial to test your script
DelStartRange.Select
'Setting the FindEndRange up for the remainder of the document form the end of the StartWord
FindEndRange.Start = DelStartRange.End
FindEndRange.End = ActiveDocument.Content.End
'Having these Selections during testing is benificial to test your script
FindEndRange.Select
'Setting the Find to look for the End Word
With FindEndRange.Find
.Text = EndWord
.Execute
'If Found then do extra script
If .Found = True Then
'Setting the Found range to the DelEndRange
Set DelEndRange = FindEndRange
'Having these Selections during testing is benificial to test your script
DelEndRange.Select
End If
End With
'Selecting the delete range
DelRange.Start = DelStartRange.Start
DelRange.End = DelEndRange.End
'Having these Selections during testing is benificial to test your script
DelRange.Select
'Remove comment to actually delete
DelRange.Delete
End If 'Ending the If Find1stRange .Found = True
Loop 'Ending the Do While .Execute Loop
End With 'Ending the Find1stRange.Find With Statement
End Sub
I want to do it this way so that I can edit my Word document without having to edit the vba code. Any help would be greatly appreciated!
Mark
Set a reference to Word (early binding) (check this article)
Read the code's comments and adjust it to fit your needs
' Set a reference to Word Library
Public Sub DeleteInWord()
' Set reference to worksheet
Dim sourceSheet As Worksheet
Set sourceSheet = ThisWorkbook.Worksheets("MySheetName")
' Define word document path
Dim wordDocPath As String
wordDocPath = "C:\Temp"
' Define word document name (include extension)
Dim wordDocName As String
wordDocName = "test.docx"
' Define start word to find in word document
Dim startWord As String
' Define end word to find in word document
Dim endWord As String
' Select the case when value in range I99 is X
Select Case sourceSheet.Range("I99").Value
Case 1
'code to delete specific paragraph in Word document
startWord = "StartWordValue1"
endWord = "EndWordValue1"
Case 2
'code to delete different paragraph in Word document
startWord = "StartWordValue2"
endWord = "EndWordValue2"
Case 3
'code to delete different paragraph in Word document
startWord = "StartWordValue3"
endWord = "EndWordValue3"
End Select
' Call delete paragraph procedure
delParagrInWordByStartEndWord wordDocPath, wordDocName, startWord, endWord
End Sub
Private Sub delParagrInWordByStartEndWord(ByVal wordDocPath As String, ByVal wordDocName As String, ByVal startWord As String, ByVal endWord As String)
' Turn off stuff
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Set a reference to word
Dim wordApp As Word.Application
Set wordApp = createWordObject(True)
' Fix document path if missing last \
If Right(wordDocPath, 1) <> "\" Then wordDocPath = wordDocPath & "\"
' Build document full path
Dim wordDocFullPath As String
wordDocFullPath = wordDocPath & wordDocName
' Open word document
Dim wordDoc As Word.Document
If Not wordFileIsOpen(wordDocFullPath) Then
Set wordDoc = wordApp.Documents.Open(wordDocFullPath)
Else
Set wordDoc = wordApp.Documents(wordDocName)
End If
'Setting up the Ranges
Dim find1stRange As Word.Range
Set find1stRange = wordDoc.Range
Dim findEndRange As Word.Range
Set findEndRange = wordDoc.Range
Dim delRange As Word.Range
Set delRange = wordDoc.Range
'Starting the Find First Word
With find1stRange.find
.Text = startWord
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
'Execute the Find
Do While .Execute
'If Found then do extra script
If .Found = True Then
'Setting the Found range to the DelStartRange
Dim delStartRange As Word.Range
Set delStartRange = find1stRange
'Having these Selections during testing is benificial to test your script
delStartRange.Select
'Setting the FindEndRange up for the remainder of the document form the end of the StartWord
findEndRange.Start = delStartRange.End
findEndRange.End = wordDoc.Content.End
'Having these Selections during testing is benificial to test your script
findEndRange.Select
'Setting the Find to look for the End Word
With findEndRange.find
.Text = endWord
.Execute
'If Found then do extra script
If .Found = True Then
'Setting the Found range to the DelEndRange
Dim delEndRange As Word.Range
Set delEndRange = findEndRange
'Having these Selections during testing is benificial to test your script
delEndRange.Select
End If
End With
'Selecting the delete range
delRange.Start = delStartRange.Start
delRange.End = delEndRange.End
'Having these Selections during testing is benificial to test your script
delRange.Select
'Remove comment to actually delete
delRange.Delete
End If 'Ending the If Find1stRange .Found = True
Loop 'Ending the Do While .Execute Loop
End With 'Ending the Find1stRange.Find With Statement
End Sub
' Credits: https://stackoverflow.com/a/47162311/1521579
Private Function createWordObject(Optional bVisible As Boolean = True) As Object
Dim tempWordObject As Object
On Error Resume Next
Set tempWordObject = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Err.Clear
On Error GoTo CleanFail
Set tempWordObject = CreateObject("Word.Application")
End If
tempWordObject.Visible = bVisible
Set createWordObject = tempWordObject
On Error GoTo 0
Exit Function
CleanFail:
Select Case Err.Number
Case Else
MsgBox "Error " & Err.Number & vbCr & _
" (" & Err.Description & ") in procedure CreateWord."
Err.Clear
End Select
End Function
' Credits: https://stackoverflow.com/a/54040283/1521579
Private Function wordFileIsOpen(wordDocFullPath As String) As Boolean
Dim ff As Long
On Error Resume Next
ff = FreeFile()
Open wordDocFullPath For Input Lock Read As #ff
Close ff
wordFileIsOpen = (Err.Number <> 0)
On Error GoTo 0
End Function

Not to wrap one with/end with, into another with/end with statement

Elegant code and code readability question
This is my code and it works fine.
There is a contract number and the date in the beginning of the Word documents I need to process, which I need to extract and write into respective cells in a spreadsheet.
My question refers to the parts of the code where one with/end with statement is wrapped in another with/end with statement. 3rd and 4th paragraph in the code, where I'm looking for the wildcards expressions.
Sub ExtractRepertorNmbrUsingWildcards()
Application.ScreenUpdating = False
Dim wordApp As Word.Application
Dim wordDoc As Word.Document
Dim excelApp As Excel.Application
Dim rng As Word.Range
Dim kompar As Word.Range
Dim ws As Worksheet
Dim regEx As Object
Dim matches As Collection
Dim match As Variant
Dim repNmbr As String
Dim cesja As Range
Dim startPos As Long
Dim endPos As Long
'Assigning object variables
Set wordApp = GetObject(, "Word.Application")
Set excelApp = GetObject(, "Excel.Application")
Set wordDoc = wordApp.ActiveDocument
Set ws = excelApp.ActiveSheet
Set rng = wordApp.ActiveDocument.Content
Set matches = New Collection
Set cesja = ActiveSheet.Range("A10:J50").Find("cesja /", , xlValues)
Debug.Print cesja.Address
With wordApp.ActiveDocument.Range
With .Find
.Text = "<[0-9 ]{1;7}/[0-9]{4}>" 'contract number
.MatchWildcards = True
.Wrap = wdFindStop
.Forward = True
.Execute
End With
If .Find.Found = True Then matches.Add Replace(.Text, " ", "") 'macro is adding it to the collection
Debug.Print "# of items is"; matches.Count
End With
With wordApp.ActiveDocument.Range
With .Find
.Text = "<[0-9]{2}.[0-9]{2}.[0-9]{4}r." 'date
.MatchWildcards = True
.Wrap = wdFindStop
.Forward = True
.Execute
End With
If .Find.Found = True Then matches.Add .Text 'macro is adding it to the same collection as above on the next free record
Debug.Print "# of items is"; matches.Count
End With
For Each match In matches
Debug.Print match
Next match
What I don't understand is why in this part of the code (and next code paragraph as well):
With wordApp.ActiveDocument.Range
With .Find
.Text = "<[0-9 ]{1;7}/[0-9]{4}>" 'contract number
.MatchWildcards = True
.Wrap = wdFindStop
.Forward = True
.Execute
End With
If .Find.Found = True Then matches.Add Replace(.Text, " ", "")
Debug.Print "# of items is"; matches.Count
End With
one with/end with statement, is wrapped in another one.
How should this part of the code be written, to avoid this unnecessary wrapping / double with/end with statement. I'm asking how a pro coder would written it?
Please correct this code, to make it efficient, good looking, readable and short.

How get paragraph number of specif text in Word VBA?

I need find an specific text in my document and get paragraph number position
This is for Excel VBA
Sub exportardatos()
'Paso 1: Declare las variables
Dim Paragraphe As Object, WordApp As Object, WordDoc As Object, WordTable As Object, WordRange As Object
File = "C:\Users\lper\Documents\FormExp.docx"
On Error Resume Next
'creationsession Word
Set WordApp = GetObject(class:="Word.Application")
'Clear the error between errors
Err.Clear
If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
If Err.Number = 429 Then
MsgBox "Microsoft Word could not be found, aborting."
GoTo EndRoutine
End If
On Error GoTo 0
WordApp.Visible = True
WordApp.Activate
'open the file .doc
Set WordDoc = WordApp.Documents.Open(File)
'Word Enumerated Constants
Const wdReplaceAll = 2
WordApp.Documents("FormExp.docx").Activate
Dim nParag As Long
Set WordRange = WordApp.ActiveDocument.Paragraphs(1).Range
For Each WordRange In WordDoc.StoryRanges
With WordApp.Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Legal"
.Wrap = wdFindContinue
.Execute
Do While .Execute = True
nParag = WordRange(0, Selection.Paragraphs(1).Range.End).Paragraphs.Count
MsgBox (nParag)
Loop
End With
Next WordRange
EndRoutine:
'Optimize Code
Application.ScreenUpdating = True
Application.EnableEvents = True
'Clear The Clipboard
Application.CutCopyMode = False
'Set WordDoc = Nothing
'Set WordApp = Nothing
MsgBox ("Ready")
End Sub
I get code error 438
Here's a quick example of how to get the paragraph number. Notice that you don't have to Activate the Word document to get this to work.
Public Sub Exportardatos()
Dim filename As String
filename = "C:\Users\lper\Documents\FormExp.docx"
Dim wordApp As Object
Set wordApp = GetObject(class:="Word.Application")
If wordApp Is Nothing Then
Set wordApp = CreateObject(class:="Word.Application")
If Err.Number > 0 Then
MsgBox "Microsoft Word cannot be found!", vbOKOnly + vbCritical
Exit Sub
End If
End If
Dim wordDoc As Object
Dim searchRange As Object
Set wordDoc = wordApp.Documents.Open(filename)
Set searchRange = wordDoc.Range
With searchRange.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Legal"
.Wrap = 0 '=wdFindStop
While .Execute(FindText:="Legal", Forward:=True)
If .found Then
Debug.Print "found in paragraph " & GetParNum(wordDoc, .Parent)
End If
Wend
End With
End Sub
Function GetParNum(ByRef doc As Object, ByRef r As Object) As Integer
'--- based on http://www.vbaexpress.com/kb/getarticle.php?kb_id=59
Dim rParagraphs As Object
Dim CurPos As Long
r.Select
CurPos = doc.Bookmarks("\startOfSel").Start
Set rParagraphs = doc.Range(Start:=0, End:=CurPos)
GetParNum = rParagraphs.Paragraphs.Count
End Function

Copy formatted text from excel to word

I have an excel sheet with two columns of strings. I track the changes of these two columns using ms-word and copy the result back to a third column. Then I copy the third column to a new word document.
The formating in Excel in Cell C3 is what I would like to transfer to word.
This is what I get at the moment. Notice the complete strike-through.
Why does it work twice but not in the third case?
I guess the root of the problem is that I remove the CR/Linefeed in the word to excel step and destroy the boundary of the strike-through-format. My goal is to get each string in one word-paragraph. If I don't remove the CR/Linefeed i get four paragraphs.
Background: In the final application the strings are going to be paragraphs of text.
Sourcecode of the excel-vba-macro (Excel 2010):
Technical remark: You may need to activate the ms-word-objects in excel-vba. (Microsoft Word 14.0 Object Library )
The macro assumes, that there a strings in the Range(A1:B3):
for example
a string a string, too
a string a new string
a string there is no try
The results will be put in the Range(C1:C3).
Option Explicit
Dim numberOfBlocks As Long
Sub main()
Dim i As Long
Dim tSht As Worksheet
Dim wordapp As Word.Application
Dim wdoc As Word.Document
Set tSht = ThisWorkbook.ActiveSheet
numberOfBlocks = 3
Application.ScreenUpdating = False
Set wordapp = CreateObject("Word.Application")
For i = 1 To numberOfBlocks
Call trackChanges(i, wordapp, tSht)
Next i
Set wdoc = wordapp.Documents.Add
Call copyChanges(tSht, wdoc)
End Sub
Sub trackChanges(i As Long, wordapp As Word.Application, tSht As Worksheet)
Dim diffDoc As Word.Document
Dim textString() As Variant
Dim j As Long
ReDim doc(2)
ReDim textString(2)
Set textString(1) = tSht.Range("A" & i)
Set textString(2) = tSht.Range("B" & i)
For j = 1 To 2
With wordapp
Set doc(j) = .Documents.Add
textString(j).Copy
doc(j).Paragraphs(1).Range.PasteSpecial
End With
Next j
wordapp.CompareDocuments OriginalDocument:=doc(1), RevisedDocument:=doc(2), _
Destination:=wdCompareDestinationNew, Granularity:=wdGranularityCharLevel
For j = 1 To 2
doc(j).Close SaveChanges:=False
Next j
Set diffDoc = wordapp.ActiveDocument
wordapp.Visible = True
'if the answer has two paragraphs, get both in one paragraph
With diffDoc.Content.Find
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
.Text = vbCrLf
.Replacement.Text = " "
.Execute Replace:=wdReplaceAll
End With
diffDoc.Range.Copy
tSht.Range("C" & i).Select
tSht.PasteSpecial Format:="HTML"
With tSht.Range("C" & i)
.WrapText = True
.Font.Name = textString(2).Font.Name
.Font.Bold = textString(2).Font.Bold
.Font.Size = textString(2).Font.Size
.Rows.AutoFit
.Interior.Color = textString(2).Interior.Color
End With
diffDoc.Close SaveChanges:=False
Application.CutCopyMode = False
Set diffDoc = Nothing
End Sub
Sub copyChanges(tSht As Worksheet, wdoc As Word.Document)
tSht.Range("C1:C" & numberOfBlocks).Copy
wdoc.Range(wdoc.Range.End - 1, wdoc.Range.End).PasteSpecial Placement:=wdInLine, DataType:=wdPasteHTML
wdoc.Tables(1).ConvertToText Separator:=wdSeparateByParagraphs
End Sub

VBA Find Text in Word Doc from Excel Not Working - Stumped

This is something half way through being built so sorry if it's confusing
I have this code where I've defined a dictionary in excel. From there I want to find text from the 'Key' in a Word Document then once it's found I want to carry on with other coding.
The problem is, I've only gotten as far as the .find part and I can't work out for the life of me why it's not finding anything.
Draw your attention to the line:
For Each Key In Dict
All I've asked after that is to find the text in string C. I know for a fact that C contains a value, since I've added a MsgBox to check and I've also added it to the Clipboard so I can try and manually find the text - and I can if I search manually
But upon running/stepping through the code the .find.execute command seems to be somewhat ignored as though it's not even trying to search through the Document and blnFound Boolean comes back False every time, jumping to Next. I also have the document (Opened by the code) displaying on my screen at the time and nothing happens on it.
Can someone advise me of what I'm doing wrong here? I'm completely baffled.
Thanks!
Sub FindReplaceInWord2()
Dim Wbk As Workbook: Set Wbk = ThisWorkbook
Dim Wrd As New Word.Application
Dim Dict As Object
Dim RefList As Range, RefElem As Range
Dim A As String
Dim B As String
Dim C As String
Dim test As New DataObject
Dim blnFound As Boolean
Wrd.Visible = True
Dim TokenDoc As Document
Set TokenDoc = Wrd.Documents.Open("\\SERVER\Client\Table.dot")
Set Dict = CreateObject("Scripting.Dictionary")
Set RefList = Wbk.Sheets("Sheet1").Range("A1:A236")
With Dict
For Each RefElem In RefList
On Error Resume Next
If Not .Exists(RefElem) And Not IsEmpty(RefElem) Then
A = RefElem.Value
.Add RefElem.Value, RefElem.Offset(0, 1).Value
B = RefElem.Value
End If
Next RefElem
End With
For Each Key In Dict
Set test = New DataObject
'MsgBox Key
test.SetText (Key)
test.PutInClipboard
C = Key
MsgBox C
With Wrd.ActiveDocument.Find
.Text = C
End With
blnFound = Wrd.ActiveDocument.Find.Execute
If blnFound = True Then
MsgBox = "Yay for working it out"
Else
MsgBox = "Boo, it didn't Work"
End If
Next Key
End Sub
PS. I've also tried
Wrd.Selection.Find.text = C
blnFound = Wrd.Selection.Find.Execute
and adding this before the find
TokenDoc.Activate
Is this what you are trying (Tried and Tested on a Local Template File)
Sub FindReplaceInWord2()
Dim Wbk As Workbook: Set Wbk = ThisWorkbook
Dim RefList As Range, RefElem As Range
Dim col As New Collection
Dim itm
Dim blnFound As Boolean
Dim Wrd As New Word.Application
Dim TokenDoc As Document
Wrd.Visible = True
'Set TokenDoc = Wrd.Documents.Open("D:\Users\SidzPc\Desktop\Temp\Table.dot")
Set TokenDoc = Wrd.Documents.Open("\\SERVER\Client\Table.dot")
Set RefList = Wbk.Sheets("Sheet1").Range("A1:A236")
For Each RefElem In RefList
On Error Resume Next
col.Add RefElem.Value, CStr(RefElem.Value)
On Error GoTo 0
Next RefElem
For Each itm In col
With Wrd.Selection.Find
.Text = itm
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
blnFound = Wrd.Selection.Find.Execute
If blnFound = True Then
MsgBox "Yay for working it out"
Else
MsgBox "Boo, it didn't Work"
End If
Next itm
End Sub

Resources