You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求修改Word宏:自动查找指定文本并插入对应Building Block

Word宏需求:自动查找指定文本并插入同名Building Block

需要一个可在Microsoft Word文档中运行的宏,实现自动查找特定文本(如“MyBB”“3000”“5000”)并插入同名Building Block的功能。日常工作中通过F3键触发已存储的Building Block,现有两段宏代码,希望修改后满足上述自动触发需求。

现有代码

代码1:InsertMyBB

Sub InsertMyBB()
'
' 假设Building Block属于"通用"类别下的自动图文集类型(wdTypeAutoText)
'
' 本代码部分基于Greg Maxey和Jay Freedman的贡献,如有错误由本人负责
' 作者:Charles Kenyon,2016年2月
'
Dim sBBName As String
Dim sTempName As String
Dim oBB As BuildingBlock
sBBName = "MyBB" '替换为你的Building Block名称
sTempName = ThisDocument.FullName '将模板的完整路径和名称存入字符串变量
On Error Resume Next
Application.Templates.LoadBuildingBlocks  ' 感谢Timothy Rylatt的建议
Set oBB = Application.Templates(sTempName).BuildingBlockTypes(wdTypeAutoText) _
.Categories("通用").BuildingBlocks(sBBName)
If Err.Number = 0 Then
    oBB.Insert Selection.Range, True
Else
    MsgBox Prompt:="在文档'" & ThisDocument.Name & "'中未找到名为'" & sBBName & "'的Building Block。", Title:="操作失败!"
End If
On Error GoTo 0
lbl_Exit:
Exit Sub
End Sub

代码2:INSERTTABLE

Sub INSERTTABLE()
Dim strSearch As String
Dim icount As Integer ' 补充声明原代码缺失的变量

    strSearch = "3000"
    
    Selection.Find.ClearFormatting
    With Selection.Find
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .MatchCase = True
        .Format = True
        .Text = strSearch
        .Execute
        Do While Selection.Find.Found = True And icount < 1000
            icount = icount + 1
            Selection.HomeKey unit:=wdStory
            Selection.Find.Execute
            Selection.Range.InsertAutoText
        Loop
    End With
   
    strSearch = "5000"
    icount = 0 ' 重置计数,避免逻辑错误
    Selection.Find.ClearFormatting
    With Selection.Find
         .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindStop
        .MatchCase = True
        .Format = True
        .Text = strSearch
        .Execute
        Do While Selection.Find.Found = True And icount < 1000
            icount = icount + 1
            Selection.HomeKey unit:=wdStory
            Selection.Find.Execute
            Selection.Range.InsertAutoText
        Loop
    End With
End Sub

注:原代码2存在icount变量未声明、查找第二个文本时计数未重置的问题,已做修正。

内容的提问来源于stack exchange,提问作者Scan 2020

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:40:21