【问题标题】:VBA Word - Finding specific text in a document and replacing the content of the paragraph following that specific textVBA Word - 在文档中查找特定文本并替换该特定文本后面的段落内容
【发布时间】:2018-08-01 08:07:53
【问题描述】:

这是我的 word 文档中的文本示例: https://www.noelshack.com/2018-31-2-1533054408-word.png

我是 VBA 新手,我正在尝试编写一个宏来查找特定文本“”““合格货币”是指基础货币和此处指定的其他货币:“并替换以下两行(填充带有一些点,不一定在同一段落中)带有文本列表(例如:欧元,美元)。

到目前为止,我已经能够使用代码循环浏览文档,找到特定的文本并对其进行编辑:

Sub FindAndFormat()
    Dim objWord As Object
    Dim wdDoc As Object
    Dim ParagraphRange As Object
    Dim intParaCount
    On Error Resume Next
    Set objWord = GetObject(, "Word.Application")
    If Err.Number <> 0 Then
        Set objWord = CreateObject("Word.Application")
    End If
    On Error GoTo 0

    Set wdDoc = objWord.Documents.Open("D:\Modele.docx")
    objWord.Visible = True
    Dim Paragraph As Word.Paragraph
    For Each Paragraph In wdDoc.Paragraphs
        Set ParagraphRange = Paragraph.Range
        ParagraphRange.Find.Text = """Eligible Currency"" means the Base Currency and each other currency specified here:"
        ParagraphRange.Find.Execute
        If ParagraphRange.Find.Found Then
            ParagraphRange.Text = """Eligible Currency"" means the Base Currency and each other currency specified here: Euro, Dollar"
        End If
    Next
End Sub

注意整行的样式是加粗和斜体。

https://www.noelshack.com/2018-31-2-1533055581-word2.png

我真正想要实现的是替换虚线:

https://www.noelshack.com/2018-31-2-1533055647-word3.png

现在我的文档中可能还有其他几条虚线,它们可能并不总是包含完全相同数量的点。

感谢您的阅读。

【问题讨论】:

  • 请花点时间阅读help center 中关于在 Stack Overflow 上提问的网站指南。您不应使用任何外部链接 - 将图片直接添加到您的问题中。

标签: vba ms-word


【解决方案1】:

尝试以下方式:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = """Eligible Currency""[!:]@:[ ….^13^l^t]{2,}"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
    .Execute
  End With
  Do While .Find.Found
    .End = .End - 1
    .Start = .Start + InStr(.Text, ":")
    .Text = Chr(11) & vbTab
    .Collapse wdCollapseEnd
    .Text = "Euro, Dollar"
    .Font.Bold = True
    .Font.Italic = True
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
Application.ScreenUpdating = True
End Sub

【讨论】:

  • 你好大脚架。非常感谢您这么快回复。你提供的确实有效。但是,这是被撕裂的:noelshack.com/2018-31-3-1533114884-word4.png 虚线向上移动后的段落开头。
  • 抱歉重复发帖。我想建立更多像这样的替代效果。您介意解释一下代码的不同部分吗?
  • 尝试删除 '.End = .End - 1' 并在 '"Euro, Dollar"' 之后插入 ' & vbCr'。该代码使用通配符查找“合格货币”,后跟任意字符串,直到找到冒号,后跟空格、省略号、句点、分段符、换行符和制表符的任意组合。然后它跳转到冒号后面的字符,然后插入手动换行符和制表符,然后是“欧元,美元”,它的格式为粗体和斜体。代码使用循环重复该过程,直到所有实例都完成。
  • 稍微好一点。 noelshack.com/2018-31-3-1533129761-word5.png 请注意,基础和货币之间有一条新线(不知道为什么)。 (b) 段落不再与 (a) 段落对齐:当我手动尝试从文档中删除虚线时也会发生这种情况。
  • 没有看到您的实际文档,很难知道问题出在哪里。我怀疑您使用的是格式不正确的文档,其中包含用于分隔文本的空段落。将文档上传到文件托管网站(例如 One Drive)并发布链接如何?
猜你喜欢
  • 1970-01-01
  • 2013-05-03
  • 2017-08-06
  • 1970-01-01
  • 2021-10-13
  • 2012-12-10
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
相关资源
最近更新 更多