在word應用程式中搜尋和替換文本是舉手之勞的事情,通過word的物件模型,我們也可以使用編程方式來實現。
Word的物件模型有比較詳細的協助文檔,放在 Office 安裝程式目錄,office 2003是在Program Files\Microsoft Office\OFFICE11\2052下,文檔本身是為VBA提供的,在這個目錄下還可以看到所有的office應用程式的VBA協助。
開啟VBAWD10.CHM,看到word的物件模型,根據以往的使用經驗,很容易在Document對象下找到Content屬性,該屬性會返回一個文檔文字部分的Range對象,從這個對象中不難取到所有的文檔內容,再用string的IndexOf()方法很容易達到目標。
object filename=""; //要開啟的文檔路徑
string strKey=""; //要搜尋的文本
object MissingValue=Type.Missing;
Word.Application wp=new Word.ApplicationClass();
Word.Document wd=wp.Documents.Open(ref filename,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue);
if (wd.Content.Text.IndexOf(strKey)>=0)
{
MessageBox.Show("文檔中包含指定的關鍵字!","搜尋結果",MessageBoxButtons.OK);
}
else
{
MessageBox.Show("文檔中沒有指定的關鍵字!","搜尋結果",MessageBoxButtons.OK);
}
不過,這種做法是很勉強的,對小文檔來說,不存在問題,對超長超大的文檔來說,這樣的實現方法已經暗埋bug了,而且是程式級的bug,因為正常的測試會很難發現問題,在使用中導致程式出現什麼樣的結果也很難量化描述。
其實,在word中已經提供了可以用作搜尋的對象Find,在物件模型上也比較容易找到,對應的說明是這樣的:該對象代表尋找操作的執行條件。Find 對象的屬性和方法與“替換”對話方塊中的選項一致。從模型上看,Find對象是Selection的成員,從範例程式碼來看似乎也是Range的成員,尋找Range的屬性,果然如此。於是修改上面的代碼:
wd.Content.Find.Text=strKey;
if (wd.Content.Find.Execute(ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue))
{
MessageBox.Show("文檔中包含指定的關鍵字!","搜尋結果",MessageBoxButtons.OK);
}
else
{
MessageBox.Show("文檔中沒有指定的關鍵字!","搜尋結果",MessageBoxButtons.OK);
}
這樣似乎也不是最好,因為我只要判斷指定的文本是不是在文檔中,而不需要知道它出現了幾次,如果有多個要搜尋的文本,難道每次都進行全文檔搜尋?假設我要搜尋的文本包含在文檔中,最好的情況是在文檔開頭就包含我要尋找的文本,最壞的情況是在文檔的最後包含要尋找的文本,如果每次取一部分文檔進行判斷,符合條件就結束本次搜尋,就可以避免每次搜尋整個文檔了。模型中的Paragraphs對象現在派上用場了,再修改一下代碼:
int i=0,iCount=0;
Word.Find wfnd;
if (wd.Paragraphs!=null && wd.Paragraphs.Count>0)
{
iCount=wd.Paragraphs.Count;
for(i=1;i<=iCount;i++)
{
wfnd=wd.Paragraphs[i].Range.Find;
wfnd.ClearFormatting();
wfnd.Text=strKey;
if (wfnd.Execute(ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue))
{
MessageBox.Show("文檔中包含指定的關鍵字!","搜尋結果",MessageBoxButtons.OK);
break;
}
}
}