Bill
Bill

Reputation: 614

Iterate through a Microsoft Word document to find and replace tables

I have some VBA code that iterates through a document to remove tables from a document. The following code works fine in VBA:

Set wrdDoc = ThisDocument
With wrdDoc
    For Each tbl In wrdDoc.Tables
        tbl.Select
        Selection.Delete
    Next tbl
End With

Unfortunately, I cannot easily translate this code to C#, presumably because there is a newer Range.Find method. Here are three things I tried, each failing.

First attempt (re-write of the VBA code):

foreach (var item in doc.Tables)
{
  item.Delete; //NOPE! No "Delete" function.
}

I tried this:

doc = app.Documents.Open(sourceFolderAndFile); //sourceFolderAndFile opens a standard word document.
var rng = doc.Tables;
foreach(var item in rng)
{
  item.Delete; //NOPE! No "Delete" function.
}

I also tried this:

doc = app.Documents.Open(sourceFolderAndFile); //sourceFolderAndFile opens a standard word document.
var rng = doc.Tables;
Range.Find.Execute(... //NOPE! No Range.Find available for the table collection.
...

Could someone please help me understand how I can use C# and Word Interop (Word 2013 and 2016) to iterate through a document, find a table, and then perform a function, like selecting it, deleting it, or replacing it?

Thanks!

Upvotes: 0

Views: 2036

Answers (1)

Bill
Bill

Reputation: 614

It took me some time to figure this answer out. With all the code samples online, I missed the need to create an app. For posterity, here is how I resolved the problem.

  1. Make sure you have a Using statement, like this:

    using MsWord = Microsoft.Office.Interop.Word;

  2. Open the document and then work with the new msWord reference, the range, and the table. I provide a basic example below:

            //open the document.
            doc = app.Documents.Open(sourceFolderAndFile, ReadOnly: true, ConfirmConversions: false);
    
            //iterate through the tables and delete them.
            foreach (MsWord.Table table in doc.Tables)
            {
                //select the area where the table is located and delete it.
                MsWord.Range rng = table.Range;
                rng.SetRange(table.Range.End, table.Range.End);
                table.Delete();
            }
    
            //don't forget doc.close and app.quit to clean up memory.
    

You can use the Range (rng) to replace the table with other items, like text, images, etc.

Upvotes: 1

Related Questions