天天看點

java資料寫入word_将資料從Excel寫入Word

我想使用Excel在列A中存儲"tag names",在列B中存儲它們關聯的"replacement text" . 當代碼運作時,它需要一次一個地收集每個标記(逐行),在整個Word文檔中搜尋這些單詞,并用相應的替代品替換它們 .

我注意到頁眉和頁腳中的特殊标簽沒有被替換 . 我轉向這篇文章(http://word.mvps.org/faqs/customization/ReplaceAnywhere.htm)并發現使用一系列範圍(或循環浏覽文檔中所有可用的故事範圍)我能夠做到這一點 .

我改進了我的代碼,正如上面連結中所建議的那樣,隻要我的代碼嵌入到我的"Normal" Word檔案中,就可以使用Word中的VBA代碼來操作另一個Word文檔 . 但是,目标是在讀取Excel檔案時使用VBA Excel操作替換 .

當我将代碼移動到Excel時,我會挂起一個讀取的自動化錯誤,

“運作時錯誤'-2147319779(8002801d)':自動化錯誤庫未注冊 . ”

我已經從審查系統資料庫到使用"Word.Application.12"代替"Word.Application"尋找答案 .

我有一台帶有Microsoft Office 2007的Windows 7,64位機器 . 我選擇了以下庫:

Excel:

Visual Basic For Applications

Microsoft Excel 12.0對象庫

OLE自動化

Microsoft Access 12.0對象庫

Microsoft Outlook 12.0對象庫

Microsoft Word 12.0對象庫

Microsoft Forms 2.0對象庫

Microsoft Office 14.0對象庫

字:

Visual Basic For Applications

Microsoft Word 12.0對象庫

OLE自動化

Microsoft Office 12.0對象庫

關于VBA,我在Excel内部操作沒有任何問題 . 通常,我會将一組字元串傳遞給這個函數,但是現在,我已經在函數内部嵌入了字元串,好像我隻計劃交換一個字元串(對于任意數量的執行個體),另一個預定的字元串 .

Function Story_Test()

Dim File As String

Dim Tag As String

Dim ReplacementString As String

Dim a As Integer

Dim WordObj As Object

Dim WordDoc As Object

Dim StoryRange As Word.Range

Dim Junk As Long

Dim BaseFile As String

'Normally, these lines would be strings which get passed in

File = "Z:\File.docx"

Tag = "{{Prepared_By}}"

ReplacementString = "Joe Somebody"

'Review currently open documents, and Set WordDoc to the correct one

'Don't worry, I already have error handling in place for the more complex code

Set WordObj = GetObject(, "Word.Application")

BaseFile = Basename(File)

For a = 1 To WordObj.Documents.Count

If WordObj.Documents(a).Name = BaseFile Then

Set WordDoc = WordObj.Documents(a)

Exit For

End If

Next a

'This is a fix provided to fix the skipped blank Header/Footer problem

Junk = WordDoc.Sections(1).Headers(1).Range.StoryType

'Okay, this is the line where we can see the error.

'When this code is run from Excel VBA, problem. From Word VBA, no problem.

'Anyone known why this is???

'***********************************************************************

For Each StoryRange In WordObj.Documents(a).StoryRanges

'***********************************************************************

Do

'All you need to know about the following function call is

' that I have a function that works to replace strings.

'It works fine provided it has valid strings and a valid StoryRange.

Call SearchAndReplaceInStory_ForVariants(StoryRange, Tag, _

ReplacementString, PreAdditive, FinalAdditive)

Set StoryRange = StoryRange.NextStoryRange

Loop Until StoryRange Is Nothing

Next StoryRange

Set WordObj = Nothing

Set WordDoc = Nothing

End Function