【问题标题】:How do I select text from the cursor position to the begining of a paragraph with VBA如何使用VBA从光标位置选择文本到段落的开头
【发布时间】:2019-12-28 04:22:26
【问题描述】:

我正在格式化大型文档中的特定类型名称。正确的格式是“术语名称 (REC) [日期]”,其中除日期外,整个短语都是斜体。我目前正在使用以下代码:

Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
        With Selection.Find
            .Text = "(REC)"
            .Replacement.Text = "*"
            .Forward = True
            .Wrap = wdFindStop
            .Format = True
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        Do While Selection.Find.Execute = True
            Selection.MoveRight Unit:=wdCharacter, Count:=1
            Selection.HomeKey Unit:=wdLine, Extend:=wdExtend
            Selection.Font.Italic = wdToggle
            Selection.EndKey Unit:=wdLine, Extend:=wdMove
        Loop

除非斜体短语超过两行,否则这很好用。我得到如下内容: "期限名称 期限 期限 期限 期限
期限 期限 期限 (REC) [日期]"
第一行没有斜体的地方。 VBA 是否有办法只在光标位置选择当前段落的开头?
请随时提出更好的方法。

【问题讨论】:

    标签: vba ms-word textselection


    【解决方案1】:

    这会选择从插入点到段落开头的所有内容。这在文档的最开头不起作用,因为没有前面的返回:

    Selection.MoveStartUntil Cset:=vbCr, Count:=wdBackward
    

    【讨论】:

      【解决方案2】:

      是的,这是可能的。有多种方法可以解决,但一种相当直接的方法是使用RangeSelection 对象的MoveStart 方法。

      就个人而言,我更喜欢使用Range 而不是Selection,因为它更灵活、更快并且“屏幕闪烁”更少。但是下面显示的方法对两者都适用,只是一样。

      Dim rngFind As Range
      
      Set rngFind = ActiveDocument.Content 'search the document body
      
      rngFind.Find.ClearFormatting
      rngFind.Find.Replacement.ClearFormatting
          With rngFind.Find
              .Text = "(REC)"
              .Replacement.Text = "*"
              .Forward = True
              .Wrap = wdFindStop
              .Format = True
              .MatchCase = False
              .MatchWholeWord = False
              .MatchWildcards = False
              .MatchSoundsLike = False
              .MatchAllWordForms = False
          End With
          Do While rngFind.Find.Execute = True
              rngFind.MoveRight Unit:=wdCharacter, Count:=1
              rngFind.MoveStart Unit:=wdParagraph, Count:=-1
              rngFind.Font.Italic = wdToggle
              rngFind.Collapse wdCollapseEnd
          Loop
      

      【讨论】:

      • 这行得通,但是,我的库无法识别 rngFind.MoveRight 我将行更改为 rngFind.Move Unit:=wdCharacter, Count:=1 并且它运行良好。它的运行速度也是我原始代码的两倍。今天,你教会了一个人钓鱼!
      • 很高兴你喜欢钓鱼...啊,我明白了我的错误:应该是MoveEnd(而不是MoveRight)。此外,您应该将最佳回答您的问题的贡献标记为“最佳”答案。您可以更改它...稍后,当您在网站上获得 15 个代表点时,您还可以 upvote 您发现的所有贡献(问题和答案)有帮助。这些操作可以帮助他人并保持网站质量 :-) 享受吧,@Thribben!
      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      • 1970-01-01
      相关资源
      最近更新 更多