private void button1_Click(object sender, EventArgs e) { var stopWatch = new Stopwatch(); stopWatch.Start(); for (int i = 0; i < 100; i++) { OpenDocument(); ElementRange elementRange = null; try { var startTagMatch = FindFirstMatch(@"\<FC\>", out elementRange); while (startTagMatch) { var startTag = new ElementRange(elementRange.Start, elementRange.End); var endTagMatch = FindFirstMatch(@"\</FC\>", out elementRange); if (!endTagMatch) { throw new InvalidOperationException("No matching end tag found"); } ReplaceWithContentControl(new ElementRange(startTag.Start, elementRange.End)); startTagMatch = FindFirstMatch(@"\<FC\>", out elementRange); } } finally { } } stopWatch.Stop(); MessageBox.Show(stopWatch.Elapsed.TotalSeconds.ToString()); }
private bool FindFirstMatch(string wordToMatch, out ElementRange elementRange) { elementRange = null; var range = application.ActiveDocument.Content; var fnd = range.Find; fnd.ClearFormatting(); fnd.Replacement.ClearFormatting(); fnd.MatchWildcards = true; fnd.Forward = true; fnd.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue; fnd.Text = wordToMatch; fnd.Execute(); if (fnd.Found) { elementRange = new ElementRange(range.Start, range.End); return true; } return false; }
private void ReplaceWithContentControl(ElementRange elementRange) { var range = application.ActiveDocument.Range(elementRange.Start, elementRange.End); range.Text = range.Text.Replace("<FC>", string.Empty).Replace("</FC>", string.Empty).Replace("\r", string.Empty); range.ContentControls.Add(Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText, range); }