I have a lot of Word documents where I need to hide text witch is formatted with a custom Word.Style type.
I’m using C# in a Windows Form and I’ve tried to open the Word documents one by one and go through all paragraphs. I then cast the paragraph style to a style object and from this I get the paragraphs Style localname.
Then if this paragraphs local style name matches one that I need to hide, then I try to take the paragraps.Range, select it, and set it to range.Font.Hidden = 1 I then try to save the document, but it document dosen’t change, so text formatted with my custom style does not change.
I've tried this so far:
using Word = Microsoft.Office.Interop.Word;
Word.Application wordApp = new Word.Application();
private void buttonOpenMany_Click(object sender, EventArgs e)
{
List<string> Styles = new List<string>();
Styles.Add("MyStyle1");
Styles.Add("MyStyle2");
Styles.Add("MyStyle3");
foreach (var item in Directory.GetFiles(textBoxWordFolder.Text,"*.docx"))
{
HideByStyleName(item, Styles);
}
MessageBox.Show("Done");
}
void HideByStyleName(string WordFile, List<string> StylesToHide)
{
wordApp.Documents.Open(WordFile);
Word.Document document = wordApp.ActiveDocument;
Word.Range rng = document.Content;
foreach (Word.Paragraph paragraph in document.Paragraphs)
{
Object styleobject = paragraph.get_Style();
string stylename = ((Word.Style)styleobject).NameLocal;
foreach (var style in StylesToHide)
{
if (stylename == style)
{
Word.Range range = paragraph.Range;
range.Select();
range.Font.Hidden = 1;
}
}
}
document.SaveAs2(WordFile);
document.Close();
}
I’ve also tried to use Range.Find.Execute but are having a hard time to figure out how to use this to find text where the Style.NameLocal =”MyCustomStyle1” And also who to replace this found range with Hidden text. Hope anyone have some input or guides.
Thank you and best regards Rasmus