天天看点

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