'''' This code is part of Document Solutions for Word demos.'' Copyright (c) MESCIUS inc. All rights reserved.''ImportsSystem.DrawingImportsSystem.LinqImportsSystem.Collections.GenericImportsSystem.Text.RegularExpressionsImportsGrapeCity.Documents.Word '' This sample loads an existing document, finds all occurrences'' of a certain string in it, And replaces that string with another one,'' also changing the character format of the replacement string.'' This sample Is almost identical to ReplaceTextFmt'' but uses PersistentRange instead of Range.'' Its primary purpose Is to illustrate the differences between'' Range And PersistentRange.PublicClassReplaceTextFmt2FunctionCreateDocx() AsGcWordDocument'' The document to replace text in:Dim path = IO.Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx")'' The text to findConsttFind = "javascript"'' The replacementConsttRepl = "ArabicaScroll" Dim doc = NewGcWordDocument() doc.Load(path) Dim runs = doc.Body.RunsDim runRanges = NewList(OfPersistentRange)(runs.Count)ForEach run In runs runRanges.Add(run.GetPersistentRange())Next ForEach rr In runRangesDim str = rr.TextDim matches = Regex.Matches(str, tFind, RegexOptions.IgnoreCase)If matches.Count = 0ThenContinueForEndIf Dim color = rr.ParentRun.Font.Color.RGB rr.Clear()Dim pos = 0ForEach m In matches rr.Runs.Add(str.Substring(pos, m.Index - pos)).Font.Color.RGB = color rr.Runs.Add(tRepl).Font.Color.RGB = Color.Red pos = m.Index + m.LengthNext rr.Runs.Add(str.Substring(pos)).Font.Color.RGB = color IfNotString.IsNullOrEmpty(rr.Runs.First.GetRange().Text) ThenThrowNew Exception("Unexpected")EndIf rr.Runs.First.Delete() '' PersistentRange Is kept up to date when the document changes,'' so it should be disposed when no longer needed to improve'' performance And reduce memory consumption: rr.Dispose()Next'' Not strictky necessary but a good practice: runRanges.Clear() '' Add a note at the end of the document doc.Body.Sections.Last.GetRange().Paragraphs.Add($"DsWord replaced '{tFind}' with '{tRepl}' on {Util.TimeNow():R}.") '' DoneReturn docEndFunctionEndClass