Checking if a table has more than one row VBA - vba

I am writing a document in word using VBA. I have made a table inside a rich text content control and also have made a button which can be pressed to open up a user form.
The problem I am facing is every time I run the code it replaces the table within the rich text control. I wanted to know if there is a 'if' function to say if there is more than one row in the table then do something else? The code I have to make the table is
Sub TableCRT()
Selection.Range.ContentControls.Add (wdContentControlRichText)
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:= _
4, defaulttablebehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
wdAutoFitFixed
With ActiveDocument.Tables(1).Rows(1)
.Cells(1).Range.Text = "heading 1"
.Cells(2).Range.Text = "heading 2"
.Cells(3).Range.Text = "heading 3"
.Cells(4).Range.Text = "heading 4"
End With
End Sub
I have also tried
Private Sub CommandButton1_Click()
If ActiveDocument.Tables(1).Count < 0 Then
Selection.Range.ContentControls.Add (wdContentControlRichText)
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=1, NumColumns:= _
4, defaulttablebehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
wdAutoFitFixed
With ActiveDocument.Tables(1).Rows(1)
.Cells(1).Range.Text = "heading 1"
.Cells(2).Range.Text = "heading 2"
.Cells(3).Range.Text = "heading 3"
.Cells(4).Range.Text = "heading 4"
End With
Dim Form As Object
Set Form = UserForm1
Form.Show
Else
Dim Form As Object
Set Form = UserForm1
Form.Show
End Sub
Thanks

This code checks if the number of content controls and tables are 0 before trying to add them. Declaring a table variable and setting the added table to that variable makes it easier to refer to the table and modify it later. Finally, if the table has more than one row, you can replace the MsgBox line with whatever processing you want to happen:
Sub TableCRT()
Dim oTable As Table
If ActiveDocument.ContentControls.Count = 0 Then
Selection.Range.ContentControls.Add (wdContentControlRichText)
End If
If ActiveDocument.Tables.Count = 0 Then
Set oTable = ActiveDocument.Tables.Add(Range:=Selection.Range, NumRows:=1, NumColumns:= _
4, defaulttablebehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
wdAutoFitFixed)
With oTable.Rows(1)
.Cells(1).Range.Text = "heading 1"
.Cells(2).Range.Text = "heading 2"
.Cells(3).Range.Text = "heading 3"
.Cells(4).Range.Text = "heading 4"
End With
Else
Set oTable = ActiveDocument.Tables(1)
End If
If oTable.Rows.Count > 1 Then
MsgBox "Hello"
'Do something here
End If
End Sub

You add every time a ContentControll but you allways refer to the first table in the document.
Try something like this
Dim g As ContentControl
Dim t As Table
Set g = Selection.Range.ContentControls.Add(wdContentControlRichText)
Set t = g.Range.Tables.Add(g.Range, 1, 4) ' change this to your code
With t.Rows(1)
.Cells(1).Range.Text = "heading 1"
.Cells(2).Range.Text = "heading 2"
.Cells(3).Range.Text = "heading 3"
.Cells(4).Range.Text = "heading 4"
End With

Related

How to create a header in Word with different color

I want to create header for word documents in a folder.The header content is same,"XYZ company" in the center and "For internal use" in the right.
Currently I use below code to do it.
Sub change(FolderPath As String)
Dim Fs, oFolder, f1, f2, f3, FColloll, s
Set Fs = CreateObject("Scripting.FileSystemObject")
Set oFolder = Fs.GetFolder(FolderPath)
Set Fcol3 = oFolder.Files
For Each f3 In Fcol3
If f3 Like "*.docx" Or f3 Like "*.pptm" Then
'Set Variable equal to Header Range
Set file = Documents.Open(filename:=f3.Path)
Set HdrRange = ActiveDocument.Sections.Item(1).Headers(wdHeaderFooterPrimary).Range
HdrText = "XYZ COMPANY For Internal Use "
HdrRange.Text = HdrText
ActiveDocument.Save
ActiveDocument.Close
End If
Next
End Sub
It worked but Now I have a new requirement, I want to change font color of "For Internal Use" to red.
I can use font.colorindex to change color. But that work on the whole header range, How do I set the "For Internal Use" as range and modify it ? Thx.
Here you are:
Const cFIU = "For internal use"
Set HdrRange = ActiveDocument.Sections.Item(1).Headers(wdHeaderFooterPrimary).Range
i = InStr(HdrRange.Text, cFIU)
For k = i To i + Len(cFIU) - 1
HdrRange.Characters(k).Font.ColorIndex = wdDarkRed
Next
Try:
Sub ColorHeader1()
With ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range
.Text = "XYZ COMPANY For Internal Use "
.SetRange .Characters(InStr(.Text, "For")).Start, .End
.Font.ColorIndex = wdRed
End With
End Sub
or
Sub ColorHeader2()
HdrText = Array("XYZ COMPANY ", "For Internal Use")
With ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range
.Text = HdrText(0)
.Collapse wdCollapseEnd
.Text = HdrText(1)
.Font.ColorIndex = wdRed
End With
End Sub
Edit2
Sub ColorHeader1()
With ActiveDocument.Sections(1)
With .Headers(wdHeaderFooterPrimary).Range
' add tabs to text for further alignment
.Text = vbTab & "XYZ COMPANY" & vbTab & "For Internal Use"
.SetRange .Characters(InStr(.Text, "For")).Start, .End
.Font.ColorIndex = wdRed
End With
With .PageSetup
pw = .PageWidth 'get the width of the page in points
rm = .RightMargin 'get the distance (in points) between the right edge of the page and the right boundary of the body text
lm = .LeftMargin 'get the distance (in points) between the left edge of the page and the left boundary of the body text.
End With
With .Headers(wdHeaderFooterPrimary).Range.ParagraphFormat.TabStops
.ClearAll ' deletes previous tabstops
.Add Position:=pw / 2 - lm, Alignment:=wdAlignTabCenter ' add center tab for "XYZ COMPANY"
.Add Position:=pw - rm - lm, Alignment:=wdAlignTabRight ' add right tab for "For Internal Use"
End With
End With
End Sub

Word VBA Loop through bookmarks of similar names

I have a userform that allows users to insert an intentionally blank page after the cover page if they need to print the document. I can get this to work just fine when i only need to insert 1 or 2 blank pages throughout the document, however I now have a new document where i need to insert a total of 14 blank pages if the userform combobox is changed to "Printable Format"
The code i use for the current document is below as reference but I think for adding so many blank pages i'm better to use a loop or find instead of this.
All of my bookmarks for where blank pages are to be added are named "Print" with sequential numbers (ie. "Print 1", Print2" etc) so i was hoping to be able to search through the document for all bookmarks containing the name "Print" but i can't seem to figure it out!
Dim answer As Integer
Dim BMBreak As Range
Dim BMBreak2 As Range
With ActiveDocument
'Insert bookmarks applicable to Printable Format
If CbxPrint.Value = "Printable Format" Then
answer = MsgBox("You have changed the document to Printable Format." & vbNewLine _
& "This will add intentionally blank pages throughout the document " & vbNewLine _
& "Do you wish to continue?", vbOKCancel, "WARNING")
If answer = vbOK Then
'Intentional blank page after title page
Set BMRange = ActiveDocument.Bookmarks("Print1").Range
BMRange.Collapse wdCollapseStart
BMRange.InsertBreak wdPageBreak
BMRange.Text = "THIS PAGE IS INTENTIONALLY BLANK"
BMRange.ParagraphFormat.SpaceBefore = 36
BMRange.ParagraphFormat.Alignment = wdAlignParagraphCenter
ActiveDocument.Bookmarks.Add "Print1", BMRange
With BMRange
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdSectionBreakContinuous
End With
With ActiveDocument.Sections(3)
.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
End With
With ActiveDocument.Sections(2)
.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
.Headers(wdHeaderFooterPrimary).Range.Delete
.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
.Footers(wdHeaderFooterPrimary).Range.Delete
End With ```
Code like the following will process any number of Print# bookmarks (presently limited to 20, which need not all exist):
Dim i As Long, BMRange As Range
With ActiveDocument
If CbxPrint.Value = "Printable Format" Then
If MsgBox("You have changed the document to Printable Format." & vbCr & _
"This will add intentionally blank pages throughout the document " & vbCr _
& "Do you wish to continue?", vbOKCancel, "WARNING") = vbOK Then
'Process bookmarks applicable to Printable Format
For i = 20 To 1 Step -1
If .Bookmarks.Exists("Print" & i) = True Then
'Intentional blank page
Set BMRange = .Bookmarks("Print" & i).Range
With BMRange
.Collapse wdCollapseEnd
.InsertBreak Type:=wdSectionBreakNextPage
.InsertBreak Type:=wdSectionBreakNextPage
.Start = .Start - 1
.Sections.Last.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
.Sections.Last.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
With .Sections.First
.Headers(wdHeaderFooterPrimary).LinkToPrevious = False
.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
.Headers(wdHeaderFooterPrimary).Range.Delete
.Footers(wdHeaderFooterPrimary).Range.Delete
.Range.InsertBefore "THIS PAGE IS INTENTIONALLY BLANK"
.Range.ParagraphFormat.SpaceBefore = 36
.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
End With
.Start = .Start - 1
.Bookmarks.Add "Print" & i, .Duplicate
End With
End If
Next
End If
End If
End With

Find the column related to comments contained in a cell of a MS Word table

I have a Word document containing a table with two columns
column 1 contains numbers
column 2 contains text
Users introduce comments on the text in column 2 (see drawing).
I can create a table putting together all the comments with this code.
How do I access the number of the other column with reference to the texts commented?
The result so far is like this:
I need the number in the first column next to the text containing the comment.
I guess there is a method similar to:
oDoc.Comments(n).Scope.Information(wdActiveEndPageNumber)
but accessing the table cell - and then I could refer to the same row and first column to grab the content of the first column?
Following is code that produces the table above. Be aware the code does not take into account that the comments are made on text belonging to table cells, Which is what I am looking for.
Sub ExtractCommentsToNewDocument()
'=========================
'Macro created 2007 by Lene Fredborg, DocTools - www.thedoctools.com
'Revised October 2013 by Lene Fredborg: Date column added to extract
'THIS MACRO IS COPYRIGHT. YOU ARE WELCOME TO USE THE MACRO BUT YOU MUST KEEP THE LINE ABOVE.
'YOU ARE NOT ALLOWED TO PUBLISH THE MACRO AS YOUR OWN, IN WHOLE OR IN PART.
'=========================
'The macro creates a new document
'and extracts all comments from the active document
'incl. metadata
'Minor adjustments are made to the styles used
'You may need to change the style settings and table layout to fit your needs
'=========================
Dim oDoc As Document
Dim oNewDoc As Document
Dim oTable As Table
Dim nCount As Long
Dim n As Long
Dim Title As String
Title = "Extract All Comments to New Document"
Set oDoc = ActiveDocument
nCount = ActiveDocument.Comments.Count
If nCount = 0 Then
MsgBox "The active document contains no comments.", vbOKOnly, Title
GoTo ExitHere
Else
'Stop if user does not click Yes
If MsgBox("Do you want to extract all comments to a new document?", _
vbYesNo + vbQuestion, Title) <> vbYes Then
GoTo ExitHere
End If
End If
Application.ScreenUpdating = False
'Create a new document for the comments, base on Normal.dot
Set oNewDoc = Documents.Add
'Set to landscape
oNewDoc.PageSetup.Orientation = wdOrientLandscape
'Insert a 4-column table for the comments
With oNewDoc
.Content = ""
Set oTable = .Tables.Add _
(range:=Selection.range, _
NumRows:=nCount + 1, _
NumColumns:=5)
End With
'Insert info in header - change date format as you wish
oNewDoc.Sections(1).Headers(wdHeaderFooterPrimary).range.Text = _
"Comments extracted from: " & oDoc.FullName & vbCr & _
"Created by: " & Application.UserName & vbCr & _
"Creation date: " & Format(Date, "MMMM d, yyyy")
'Adjust the Normal style and Header style
With oNewDoc.Styles(wdStyleNormal)
.Font.Name = "Arial"
.Font.Size = 10
.ParagraphFormat.LeftIndent = 0
.ParagraphFormat.SpaceAfter = 6
End With
With oNewDoc.Styles(wdStyleHeader)
.Font.Size = 8
.ParagraphFormat.SpaceAfter = 0
End With
'Format the table appropriately
With oTable
.range.Style = wdStyleNormal
.AllowAutoFit = False
.PreferredWidthType = wdPreferredWidthPercent
.PreferredWidth = 100
.Columns.PreferredWidthType = wdPreferredWidthPercent
.Columns(1).PreferredWidth = 5
.Columns(2).PreferredWidth = 23
.Columns(3).PreferredWidth = 42
.Columns(4).PreferredWidth = 18
.Columns(5).PreferredWidth = 12
.Rows(1).HeadingFormat = True
End With
'Insert table headings
With oTable.Rows(1)
.range.Font.Bold = True
.Cells(1).range.Text = "Page"
.Cells(2).range.Text = "Code"
.Cells(3).range.Text = "Text"
.Cells(4).range.Text = "Interview"
.Cells(5).range.Text = "Date"
End With
'Get info from each comment from oDoc and insert in table
For n = 1 To nCount
With oTable.Rows(n + 1)
'Page number
.Cells(1).range.Text = _
oDoc.Comments(n).Scope.Information(wdActiveEndPageNumber)
'The comment itself
.Cells(2).range.Text = oDoc.Comments(n).range.Text
'The text marked by the comment
.Cells(3).range.Text = oDoc.Comments(n).Scope
'The comment author
.Cells(4).range.Text = oDoc.Comments(n).Author
'The comment date in format dd-MMM-yyyy
.Cells(5).range.Text = Format(oDoc.Comments(n).Date, "dd-MMM-yyyy")
End With
Next n
Application.ScreenUpdating = True
Application.ScreenRefresh
oNewDoc.Activate
MsgBox nCount & " comments found. Finished creating comments document.", vbOKOnly, Title
ExitHere:
Set oDoc = Nothing
Set oNewDoc = Nothing
Set oTable = Nothing
End Sub
After:
.Cells(3).Range.Text = oDoc.Comments(n).Scope
Insert:
If oDoc.Comments(n).Scope.Information(wdWithInTable) = True Then
If oDoc.Comments(n).Scope.Cells(1).ColumnIndex > 1 Then
.Cells(3).Range.InsertBefore Split(oDoc.Comments(n).Scope.Rows(1).Cells(1).Range.Text, vbCr)(0) & vbTab
End If
End If

OnAction with parameters

This is my first ever question on SO even I come here regularly (I've always find my answer without having to ask until today). I know this question I've already posted but for some reason i doesn't work for me.
I'm trying to get a right click submenu with a list of every numbered items in my word document. The purpose of it is to insert in a click the numbered and the content text of my numbered item in my document.
The problem is I don't know how to affect each .OnAction (to insert the numbered item in my document) and each .Caption (to show the number and content text of my numbered item in my menu) with a different variable (one for each numbered item). There is probably a problem with my quotes but I cannot see any other solution.
My code is the following :
Option Explicit
Sub ControlButtonNumberedItems()
'Parameters for NumberedItems
Dim i As Integer
i = 1
Dim NumberedItems As Integer
NumberedItems = ActiveDocument.CountNumberedItems
'Parameters for CommanBar
Dim MenuButton As CommandBar
Set MenuButton = Application.CommandBars("Text")
Dim SubMenuButton As CommandBarControl
Set SubMenuButton = MenuButton.Controls.Add(Type:=msoControlPopup, Before:=1)
With SubMenuButton
.Caption = "NumberedItems"
.Tag = "My_Tag"
While i <= NumberedItems
With .Controls.Add(Type:=msoControlButton)
.OnAction = "'InsertNumberedItem""i""'"
.FaceId = 38
.Caption = "MyCaption"
End With
i = i + 1
Wend
End With
End Sub
Sub InsertEvidence(i As Integer)
'Insert NumberRelativeContext
Selection.InsertCrossReference ReferenceType:=wdRefTypeNumberedItem, _
ReferenceKind:=wdNumberRelativeContext, _
ReferenceItem:=i, _
InsertAsHyperlink:=True, _
SeparatorString:=" "
Selection.TypeText Text:=" "
'Insert ContentText
Selection.InsertCrossReference ReferenceType:=wdRefTypeNumberedItem, _
ReferenceKind:=wdContentText, _
ReferenceItem:=i, _
InsertAsHyperlink:=True, _
SeparatorString:=" "
'Text form
Selection.Expand Unit:=wdLine
Selection.Font.Bold = wdToggle
Selection.Font.Italic = wdToggle
Selection.ParagraphFormat.Alignment = wdAlignParagraphRight
Selection.ParagraphFormat.SpaceBefore = 6
End Sub
Sub ResetRightClick()
Application.CommandBars("Text").Reset
End Sub
Thank you in advance for any help. Please let me know if you need any other information.
I didn't know that Word VBA is different from Excel: see the accepted answer here:
VBA Pass arguments with .onAction
This worked for me (just the code needed to show how parameters can be passed):
Sub ControlButtonNumberedItems()
Dim i As Integer
Dim NumberedItems As Integer
'Parameters for CommanBar
Dim MenuButton As CommandBar
Set MenuButton = Application.CommandBars("Text")
Dim SubMenuButton As CommandBarControl
Set SubMenuButton = MenuButton.Controls.Add(Type:=msoControlPopup, Before:=1)
With SubMenuButton
.Caption = "NumberedItems"
.Tag = "My_Tag"
For i = 1 To 5
With .Controls.Add(Type:=msoControlButton)
.OnAction = "InsertNumberedItem"
.FaceId = 38
.Parameter = i
.Caption = "MyCaption " & i
End With
Next i
End With
End Sub
Public Sub InsertNumberedItem()
MsgBox "got " & CommandBars.ActionControl.Parameter
End Sub
Sub ResetRightClick()
Application.CommandBars("Text").Reset
End Sub

Using Multiple wildcard searches in Word 2007 with VBA

I have VBA code that runs through a document and identifies acronyms using wildcards and places them in a separate word document. Some of my writers don't always follow the proper style guides for acronyms so I'm running four different scripts to find all the possible acronyms. It's time consuming and I end up with multiple documents. Is there a method to run multiple searches from one script and have all the results placed in the separate document. Truth in Advertising: I found this script on the 'net, but I've been playing with it to attempt to make it do some other features. Adding current script:
Sub ExtractVariousValuesACRONYMSToNewDocument()
'The macro creates a new document,
'finds all words consisting of 2 or more uppercase letters
'in the active document and inserts the words
'in column 1 of a 3-column table in the new document
'Each acronym is added only once
'Use column 2 for definitions
'Page number of first occurrence is added by the macro in column 3
'Minor adjustments are made to the styles used
'You may need to change the style settings and table layout to fit your needs
'=========================
Dim oDoc_Source As Document
Dim oDoc_Target As Document
Dim strListSep As String
Dim strAcronym As String
Dim oTable As Table
Dim oRange As Range
Dim n As Long
Dim strAllFound As String
Dim Title As String
Dim Msg As String
Title = "Extract Acronyms to New Document"
'Show msg - stop if user does not click Yes
Msg = "This macro finds all words consisting of 2 or more " & _
"uppercase letters and extracts the words to a table " & _
"in a new document where you can add definitions." & vbCr & vbCr & _
"Do you want to continue?"
If MsgBox(Msg, vbYesNo + vbQuestion, Title) <> vbYes Then
Exit Sub
End If
Application.ScreenUpdating = False
'Find the list separator from international settings
'May be a comma or semicolon depending on the country
strListSep = Application.International(wdListSeparator)
'Start a string to be used for storing names of acronyms found
strAllFound = "#"
Set oDoc_Source = ActiveDocument
'Create new document for acronyms
Set oDoc_Target = Documents.Add
With oDoc_Target
'Make sure document is empty
.Range = ""
'Insert info in header - change date format as you wish
.PageSetup.TopMargin = CentimetersToPoints(3)
.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text = _
"Acronyms extracted from: " & oDoc_Source.FullName & vbCr & _
"Created by: " & Application.UserName & vbCr & _
"Creation date: " & Format(Date, "MMMM d, yyyy")
'Adjust the Normal style and Header style
With .Styles(wdStyleNormal)
.Font.Name = "Arial"
.Font.Size = 10
.ParagraphFormat.LeftIndent = 0
.ParagraphFormat.SpaceAfter = 6
End With
With .Styles(wdStyleHeader)
.Font.Size = 8
.ParagraphFormat.SpaceAfter = 0
End With
'Insert a table with room for acronym and definition
Set oTable = .Tables.Add(Range:=.Range, NumRows:=2, NumColumns:=3)
With oTable
'Format the table a bit
'Insert headings
.Range.Style = wdStyleNormal
.AllowAutoFit = False
.Cell(1, 1).Range.Text = "Acronym"
.Cell(1, 2).Range.Text = "Definition"
.Cell(1, 3).Range.Text = "Page"
'Set row as heading row
.Rows(1).HeadingFormat = True
.Rows(1).Range.Font.Bold = True
.PreferredWidthType = wdPreferredWidthPercent
.Columns(1).PreferredWidth = 20
.Columns(2).PreferredWidth = 70
.Columns(3).PreferredWidth = 10
End With
End With
With oDoc_Source
Set oRange = .Range
n = 1 'used to count below
With oRange.Find
'Use wildcard search to find strings consisting of 2 or more uppercase letters
'Set the search conditions
'NOTE: If you want to find acronyms with e.g. 2 or more letters,
'change 3 to 2 in the line below
.Text = "<[A-Z]{2" & strListSep & "}>"
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = True
.MatchWildcards = True
'Perform the search
Do While .Execute
'Continue while found
strAcronym = oRange
'Insert in target doc
'If strAcronym is already in strAllFound, do not add again
If InStr(1, strAllFound, "#" & strAcronym & "#") = 0 Then
'Add new row in table from second acronym
If n > 1 Then oTable.Rows.Add
'Was not found before
strAllFound = strAllFound & strAcronym & "#"
'Insert in column 1 in oTable
'Compensate for heading row
With oTable
.Cell(n + 1, 1).Range.Text = strAcronym
'Insert page number in column 3
.Cell(n + 1, 3).Range.Text = oRange.Information(wdActiveEndPageNumber)
End With
n = n + 1
End If
Loop
End With
End With
'Sort the acronyms alphabetically - skip if only 1 found
If n > 2 Then
With Selection
.Sort ExcludeHeader:=True, FieldNumber:="Column 1", SortFieldType _
:=wdSortFieldAlphanumeric, SortOrder:=wdSortOrderAscending
'Go to start of document
.HomeKey (wdStory)
End With
End If
Application.ScreenUpdating = True
'If no acronyms found, show msg and close new document without saving
'Else keep open
If n = 1 Then
Msg = "No acronyms found."
oDoc_Target.Close savechanges:=wdDoNotSaveChanges
Else
Msg = "Finished extracting " & n - 1 & " acronymn(s) to a new document."
End If
MsgBox Msg, vbOKOnly, Title
'Clean up
Set oRange = Nothing
Set oDoc_Source = Nothing
Set oDoc_Target = Nothing
Set oTable = Nothing
End Sub
The best solution would be one searching pattern for all cases. Word hasn't full regular expressions, it is not always possible. Write all four patterns, maybe there is a way for join them into one super-pattern.
The second possibility is running multiple times the same algorithm in one macro, something like this:
Sub Example()
Dim patterns As String
Dim pts() As String
'list of patterns for each run delimited by a delimiter - comma in this example
patterns = "first pattern, second pattern, and so on"
pts = Split(patterns, ",") 'the second parameter is a delimiter
Dim i As Integer
For i = 0 To UBound(pts)
'do your subroutine for each searching pattern
Next i
'save document with result
End Sub
For better answer give us more details, please.