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
Related
The following is an Excel VBA code that aims to copy the selected excel range and paste it into a Word document at the very next paragraph below the current cursor position.
However, there are issues with the code:
1- How to use the word document I set by Set WordDoc = WordApp.Documents("Test.docx") so that I can avoid pasting into another document by mistake?
2- Why do both instances of MoveDown fail when explicitly setting their options to Unit:=wdparagraph, Count:=1, Extend:=wdMove, and get the error
Run-time error '4120': Bad parameter
Sub CopyTableToWord()
Selection.Copy
Dim WordApp As Object
Set WordApp = GetObject(, "Word.Application")
WordApp.Visible = True
Dim WordDoc As Object
Set WordDoc = WordApp.Documents("Test.docx")
' cursor position
WordApp.Selection.Range.Characters.Last.InsertParagraphAfter
WordApp.Selection.MoveDown 'Unit:=wdparagraph, Count:=1, Extend:=wdMove
With WordApp.Selection
.Range.PasteExcelTable False, False, False
With .Range.Tables(1)
.Range.ParagraphFormat.SpaceBefore = 0
.Range.ParagraphFormat.SpaceAfter = 0
.AutoFitBehavior 2 'wdAutoFitWindow
.Range.Select
End With
' move out of the table, then add space after it
' to move the Word cursor to the new position
' of the next table to be pasted
.Collapse wdCollapseEnd
.Range.InsertParagraphAfter
.MoveDown 'Unit:=wdParagraph, Count:=1, Extend:=wdMove
End With
End Sub
For copying & pasting tables one at a time and with only a single instance of Word running, you could use something like:
Sub PasteAndFormatTableInWord()
Application.ScreenUpdating = False
Dim wdApp As Word.Application, wdDoc As Word.Document
Const StrDocNm As String = "Test.docx"
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If wdApp Is Nothing Then Set wdApp = CreateObject("Word.Application")
On Error GoTo 0
With wdApp
'Check if the document is open.
For Each wdDoc In .Documents
If wdDoc.Name = StrDocNm Then Exit For
Next
If wdDoc Is Nothing Then
MsgBox "Your '" & StrDocNm & "' document isn't open." & vbCr & _
"Please open the document and select the insertion point.", vbExclamation: Exit Sub
End If
wdDoc.Activate
With .Selection
.Collapse 1 'wdCollapseStart
With .Range
.PasteAndFormat 16 'wdFormatOriginalFormatting
With .Tables(1)
.AutoFitBehavior 2 'wdAutoFitWindow
.Cell(1, 1).PreferredWidthType = 3 'wdPreferredWidthPoints
.Cell(1, 1).PreferredWidth = 75
.Range.Characters.Last.Next.InsertBefore vbCrLf
End With
.Start = .Tables(1).Range.End + 1
.Collapse 0 'wdCollapseEnd
.Select
End With
End With
wdDoc.Save
End With
Application.ScreenUpdating = False
End Sub
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.
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
I am using Excel VBA to open a document in Word. Once the document is open the goal is to search for "InsuranceCompanyName" and replace it with the company's name.
I have tried
wordDoc.Find.Execute FindText:="InsuranceCompanyName", ReplaceWith:="Fake Ins Co"
and
wordDoc.Replace What:="InsuranceCompanyName", Replacement:="Fake Ins Co"
and also
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.Find
.Text = "InsuranceCompanyName"
.Replacement.Text = "Fake Ins Co"
.WrapText = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
Next myStoryRange
The full code is listed below.
Sub FindReplace()
Dim wordApp As Object
Dim wordDoc As Object
Dim myStoryRange As Range
'sets up the word app
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = True
'opens the document that we need to search through
Set wordDoc = wordDoc = wordApp.Documents.Open("C:\Users\cd\LEQdoc.docx")
'here is where the find and replace code would go
End Sub
For the first method I get the error:
Object doesn't support this property or method.
For the second: the same error
The third method:
argument not optional
in regards to the .Find in
With myStoryRange.Find
Try this code
Option Explicit
Const wdReplaceAll = 2
Sub FindReplace()
Dim wordApp As Object
Dim wordDoc As Object
Dim myStoryRange As Object
'~~> Sets up the word app
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = True
'~~> Opens the document that we need to search through
Set wordDoc = wordApp.Documents.Open("C:\Users\routs\Desktop\Sample.docx")
For Each myStoryRange In wordDoc.StoryRanges
With myStoryRange.Find
.Text = "InsuranceCompanyName"
.Replacement.Text = "Fake Ins Co"
.Execute Replace:=wdReplaceAll
End With
Next myStoryRange
End Sub
In Action
I'm trying to create a code that reads a dynamic Excel table into an existing Word document and changes some variables in the document (for example %Username%)
The code below gives me an "Locked for editing" error by myself, but that isn't the case.
Can someone see what I have to change in the code?
The code is:
Sub Export_Table_Word()
'Word objects.
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdbmRange As Word.Range
'Excel objects.
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnReport As Range
'Path of Word Template
Dim stPathTemplate As String
Dim stPathSave As String
'Dynamic Replace variables
Dim UserName As String
Dim StrFind
Dim StrRepl As String
'Loop variable
Dim i As Long
Dim msWord As Object
Set msWord = CreateObject("Word.Application")
'Define replacement variables
UserName = Application.UserName
sFirst = Split(UserName, " ")(0) 'Firstname 'sFirst = Split(UserName, ",")(1) 'Firstname
sLast = Split(UserName, " ")(1) 'Lastname
sUserName = Left(sFirst, 1) & sLast 'First letter of firstname and lastname
sFullName = sFirst & " " & sLast 'Full name
StrFind = "%User_Name%,%Full_name%, %Date%" 'Strings to be replaced in the word document
StrRepl = sUserName & "*" & sFullName & "*" & " " & Date 'Replaced by
'Initialize Path word template
stPathTemplate = "C:\Users\xxx\Desktop\VBA_TEST\VBA_Automation.docx"
stPathSave = "C:\Users\xxx\Desktop\VBA_TEST\Finished.docx"
'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets(1)
Set rnReport = wsSheet.Range("D2:D7")
'Initialize the Word objets.
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open(stPathTemplate)
Set wdbmRange = wdDoc.Bookmarks("Report").Range
'If the macro has been run before, clean up any artifacts before trying to paste the table in again.
On Error Resume Next
With wdDoc.InlineShapes(1)
.Select
.Delete
End With
On Error GoTo 0
'Turn off screen updating.
Application.ScreenUpdating = True
With wdDoc
.Visible = True
.Documents.Open (stPathTemplate)
.Activate
With .ActiveDocument.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
For i = 0 To UBound(Split(StrFind, ",")) 'Loop to replace all the defined dynamic strings
.Text = Split(StrFind, ",")(i)
.Replacement.Text = Split(StrRepl, "*")(i)
.Execute Replace:=wdReplaceAll
Next i
.Forward = True
.Wrap = 1 'FindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=2 'wdReplaceAll (WdReplace Enumeration)
End With
End With
'Copy the report to the clipboard.
rnReport.Copy
'Select the range defined by the "Report" bookmark and paste in the report from clipboard.
With wdbmRange
.Select
.Paste
End With
'Save and close the Word doc.
With wdDoc
'.Save
.SaveAs2 Filename:=stPathSave, _
FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
.Close
End With
'Quit Word.
wdApp.Quit
'Null out your variables.
Set wdbmRange = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
'Clear out the clipboard, and turn screen updating back on.
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
MsgBox ("Done")
End Sub