如何查找和替换?

时间:2018-11-05 13:57:01

标签: vba ms-word

我有这段代码,我想知道它是否可以更短?

我是VBA的新手,我从宏记录器开始。该功能是“查找并替换”。我知道必须有一个简短的代码。

Sub TOs()
    '
    ' MACRO_TOS Macro    
    '    
    '
    Selection.Find.ClearFormatting    
    Selection.Find.Replacement.ClearFormatting    

    With Selection.Find
        .Text = "To=____________________________"   
        .Replacement.Text = ""    
        .Forward = True    
        .Wrap = wdFindContinue    
        .Format = False    
        .MatchCase = False    
        .MatchWholeWord = False    
        .MatchWildcards = False    
        .MatchSoundsLike = False    
        .MatchAllWordForms = False    
    End With

    Selection.Find.Execute

    With Selection    
        If .Find.Forward = True Then    
            .Collapse Direction:=wdCollapseStart    
        Else    
            .Collapse Direction:=wdCollapseEnd    
        End If  

        .Find.Execute Replace:=wdReplaceOne   

        If .Find.Forward = True Then    
            .Collapse Direction:=wdCollapseEnd    
        Else    
            .Collapse Direction:=wdCollapseStart    
        End If

        .Find.Execute    
    End With    
End Sub

2 个答案:

答案 0 :(得分:2)

  1. 您可以使用import org.hibernate.jpa.event.internal.core.JpaPostDeleteEventListener; import org.hibernate.jpa.event.internal.core.JpaPostInsertEventListener; import org.hibernate.jpa.event.internal.core.JpaPostLoadEventListener; import org.hibernate.jpa.event.internal.core.JpaPostUpdateEventListener; import org.hibernate.jpa.event.internal.jpa.CallbackBuilderLegacyImpl; import org.hibernate.jpa.event.internal.jpa.CallbackRegistryImpl; import org.hibernate.jpa.event.spi.jpa.CallbackBuilder; import org.hibernate.jpa.event.spi.jpa.ListenerFactory; import org.hibernate.jpa.event.spi.jpa.ListenerFactoryBuilder; 一次替换所有内容。
  2. 您可以使用Replace:=wdReplaceAll允许.MatchWildcards = True中的通配符出现空格。例如: .Text

示例:

.Text = "To*=*____________________________"

答案 1 :(得分:0)

MatchCase,MatchWholeWord,MatchAllWordForms和MatchSoundsLike都不能与通配符一起使用。因此,代码可以简化为:

Sub RemoveTo()
With Selection.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .Text = "To[ =]@[_]{1,}"
  .Replacement.Text = ""
  .Forward = True
  .Format = False
  .Wrap = wdFindContinue
  .MatchWildcards = True
  .Execute Replace:=wdReplaceAll
End With
End Sub

甚至:

Sub RemoveTo()
With Selection.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .Execute FindText:="To[ =]@[_]{1,}", ReplaceWith:="", MatchWildcards:=True, _
    Forward:=True, Format:=False, Wrap:=wdFindContinue, Replace:=wdReplaceAll
End With
End Sub