【问题标题】:Iterating through excel document to replace words in word遍历excel文档以替换word中的单词
【发布时间】:2015-10-05 01:49:40
【问题描述】:

我有一个两列 100 行的 excel 文档。一列是要在 word 文档中查找的单词,第二列是我要替换搜索到的单词的单词。

我想遍历 excel 表中的每一行,并使用输入在 word 文档中进行搜索和替换。

我有在 Access 中使用 VBA 的经验,但我以前从未在 Word 或 Excel 中使用过它,我很困惑。

我认为会起作用的功能是这样的:

function replace(find,replace)
with activedocument.content.find
.forward=True
.wrap=wdFindContinue
.Execute fintext:=find,replacewith:=replace,matchcase:=False,matchwholeword:=True
end with
end function

在访问中,您将在事件中调用该函数,但 word 没有事件。我只想运行代码。当我选择运行一个要求我创建宏的表单时,我会迷路。

如何在 Word 中运行 vba 代码?

谢谢

【问题讨论】:

    标签: vba excel ms-word


    【解决方案1】:

    要在 Word 中运行 VBA 代码,请按 Alt-F8

    它将显示一个表格,其中包含文档中所有可用的公共子或函数。

    例如:

    • 打开 Word 文件和 VBA 编辑器窗口 (Alt-F11)
    • 点击菜单项:插入 -> 模块
    • 创建与此类似的 myFindAndReplace Sub:

    Option Explicit
    
    Public Sub myFindAndReplace()
    
        Const MAX_ITEMS As Long = 3
        Dim i As Long, arr1(1 To MAX_ITEMS) As String, arr2(1 To MAX_ITEMS) As String
    
        arr1(1) = "find1"
        arr1(2) = "find2"
        arr1(3) = "find3"
    
        arr2(1) = "replace1"
        arr2(2) = "replace2"
        arr2(3) = "replace3"
    
        With Application.ActiveDocument.Content.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            For i = 1 To MAX_ITEMS
                .Text = arr1(i)
                .Replacement.Text = arr2(i)
                .Forward = True
                .Wrap = wdFindContinue
                .Format = False
                .MatchCase = False
                .MatchWholeWord = False
                .MatchWildcards = False
                .MatchSoundsLike = False
                .MatchAllWordForms = False
                .Execute Replace:=wdReplaceAll
            Next
        End With
    End Sub
    

    在 Word 中单击 Alt-F8,您将获得可用的宏:


    Word 在 VBA 模块 ThisDocument 中有以下事件(在您的文件名的项目下):

    • Document_BuildingBlockInsert()
    • Document_Close()
    • Document_ContentControlAfterAdd()
    • Document_ContentControlBeforeContentUpdate()
    • Document_ContentControlBeforeDelete()
    • Document_ContentControlBeforeStoreUpdate()
    • Document_ContentControlOnEnter()
    • Document_ContentControlOnExit()
    • Document_New()
    • Document_Open()
    • Document_Sync()
    • Document_XMLAfterInsert()
    • Document_XMLBeforeDelete()

    现在你可以

    1. 构建整个两个数组(在 Word 中)并直接在代码中使用它们,如示例 Sub

    2. 或者打开Excel文件,遍历每一行,在Word中进行替换

    选项2更复杂

    【讨论】:

    • 非常感谢您提供的图片和详尽的解释。我现在可以在 Word 中使用 Access 中的 VBA 技能了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    • 2019-02-21
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    相关资源
    最近更新 更多