0

I have created word doc with merge fields. Merge fields in word doc would look like this:

{ MERGEFIELD TestValue }.

What I need to do is to remove the white space at the beginning and end of the field. So it should look like this:

{MERGEFIELD TestValue}.

I'm using Microsoft.Office.Interop.Word to generate the document.

Here is sample of the code:

Word.Field fldMerge;
bool bFound;

oRng.Find.ClearFormatting();
oRng.Find.Forward = true;
oRng.Find.Wrap = Word.WdFindWrap.wdFindStop;                
oRng.Find.Format = false;
oRng.Find.MatchCase = false;
oRng.Find.MatchWholeWord = false;
oRng.Find.MatchWildcards = false;
oRng.Find.MatchSoundsLike = false;
oRng.Find.MatchAllWordForms = false;                
oRng.Find.Text = sOldTag.Trim();                
bFound = oRng.Find.Execute();

while (bFound)
{
    fldMerge = oRng.Fields.Add(oRng, Word.WdFieldType.wdFieldMergeField, sNewTag.Trim(), false);                    
    oRng = fldMerge.Result;
    oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
    oRng.MoveStart(Word.WdUnits.wdCharacter, 2);
    oRng.End = oRng.Document.Content.End;
    oRng.Find.Text = sOldTag.Trim();
    bFound = oRng.Find.Execute();
}

This is sample of the code of how to create the merge field

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
  • do a search for the `Trim()` method for a `String` – jazb Aug 09 '19 at 06:30
  • WHY do you need to do this? It could be done by editing the `Field.Code` but I can't imagine why that would be necessary... – Cindy Meister Aug 09 '19 at 14:24
  • thank you for your reply. The reason I want to remove the white space is because I'm trying to integrate with another third party company to generate their reporting. And for some reason if there is a space it won't pull their data unless i remove the spaces. Is it possible to show me a sample code of how to do that. Regards, Sam – Sam Khanjar Aug 10 '19 at 09:31

0 Answers0