2010-08-10

Word 套版 With Office Word 2007 問題

網路上找的大部份都是這樣的範例,當成功執行之後[Name]會被換成Boss
一切都是這樣的美好,因為我們全公司都使用Office 2003


Dim word As New Microsoft.Office.Interop.Word.Application
Dim doc As Microsoft.Office.Interop.Word.Document
Try
doc = word.Documents.Open("C:\1.doc")
doc.Activate()
Dim myStoryRange As Microsoft.Office.Interop.Word.Range
For Each myStoryRange In doc.StoryRanges

With myStoryRange.Find
.Text = "[Name]"
.Replacement.Text = "Boss"
.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue
.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
End With
Next myStoryRange
word.Visible = True
Catch ex As COMException
MessageBox.Show("Error accessing Word document.")
Finally
doc = Nothing
word = Nothing
End Try


可是好景不常,噹噹噹~踢到了一個鐵板
---------------------------
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at Word.Find.set_Text(String prop)
---------------------------
網路上眾說紛雲,
1.有人說是記憶體壞掉
2.也有說是因為Office 2003和Office 2007同時安裝的關係

嗯~發生問題的User真的是使用Office 2007
長話短說,為了這個問題在茫茫網海中花了二天半的時間
最後當然是找到了解決方式
原來只要改一個字
把Word.WdFindWrap.wdFindContinue改成Word.WdFindWrap.wdFindAsk
問題解決!

如果套板的文字只要換一次可以把wdReplaceAll改成wdReplaceOne
這樣可以節省一些時間喔!

Case close.

0 comments: