2016-12-14 57 views
0

我有一些VBA代码遍历文档以从文档中删除表格。下面的代码在VBA正常工作:遍历Microsoft Word文档来查找和替换表格

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

不幸的是,我不能轻易因为有一个新的Range.Find方法翻译这个代码为C#,大概。以下是我尝试过的三件事,每件都失败了。

第一次尝试(VBA代码重新写):

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

我尝试这样做:

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. 
} 

我也试过这样:

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. 
... 

可能有人请帮助我了解如何使用C#和Word Interop(Word 2013和2016)遍历文档,查找表,然后按形成一个功能,就像选择它,删除它或替换它一样?

谢谢!

回答

0

我花了一些时间来解答这个问题。所有的代码示例都在线,我错过了创建应用程序的需求。为了后代,这是我如何解决问题。

  1. 确保你有一个使用的语句,像这样:

    使用MSWORD =的Microsoft.Office.Interop.Word;

  2. 打开文档,然后使用新的msWord引用,范围和表格。我下面提供一个基本的例子:

     //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. 
    

可以使用范围(RNG)与其他项目替换表,如文本,图像等

+0

也许你应该使用一个向后的循环?这是您通常要从集合中删除项目时所要执行的操作。你为什么使用SetRange? – Jbjstam

+0

据我所知,没有必要做一个后向循环,因为所有的表格都是从头到尾找到的。至于SetRange,这是最好的方式(据我所知)选择表格然后删除它。如果你有更好的选择,我都是耳朵:) – Bill