首页 > 解决方案 > 查找和删除文本

问题描述

我在 Word 中编写代码来查找文档中的“[编辑]”链接、断开超链接并删除文本。

我想调整它以在 Outlook 中运行。我已经转到工具>引用以允许 Outlook 访问 Word 对象库,并在我的“DeleteEditLinks”宏之前插入以下代码:

    Dim Ins As Outlook.Inspector
    Dim Document As Word.Document
    Dim Word As Word.Application
    Dim Selection As Word.Selection
    
    Set Ins = Application.ActiveInspector
    Set Document = Ins.WordEditor
    Set Word = Document.Application
    Set Selection = Word.Selection

最终代码如下所示:

Public Sub DeleteEditLinks()
    Dim Ins As Outlook.Inspector
    Dim Document As Word.Document
    Dim Word As Word.Application
    Dim Selection As Word.Selection
    
    Set Ins = Application.ActiveInspector
    Set Document = Ins.WordEditor
    Set Word = Document.Application
    Set Selection = Word.Selection
    
    Dim oField As Field ' breaks hyperlinks of "[edit]" links, and deletes them
    For Each oField In ActiveDocument.Fields
        If oField.Type = wdFieldHyperlink Then
            If Left(oField.Result, 4) = "edit" Then
                oField.Unlink
            End If
        End If
    Next
    Set oField = Nothing
      
    Dim sample
    sample = "[edit]"
    
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = sample
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

如何调整它以在 Outlook 电子邮件的文本上运行?

标签: vbaoutlookms-word

解决方案


我不确定 Fields 对象必须如何出现在 Outlook 中,以及您想要实现的目标,但是!.. 我在您的代码中发现了基本问题,因此,我的解决方案可能会有所帮助。

  • 您在其中引用 ActiveDocument,因为它是 Outlook 对象集合的一部分。它不是,所以你需要参考你从检查器中正确创建的 Document 对象。与选择相同。
  • 我使用了后期绑定(Dim oField As Object),不确定是否使用早期绑定和“工具>引用”选项也有这个问题,但是单词常量 wdFindContinue 未被识别,所以我使用了它们的值(只是用谷歌搜索)。

因此,如果在您的目标电子邮件中以某种方式存在字段 - 您下面的更新代码应该可以工作......如果不是这样,请写。

Public Sub DeleteEditLinks()

Dim Ins As Outlook.Inspector
Dim Document As Object
Dim oField As Object
Dim sample As String

Set Ins = Application.ActiveInspector
Set Document = CreateObject("Word.Document")
Set Document = Ins.WordEditor

For Each oField In Document.Fields
  If oField.Type = 88 Then
    If Left(oField.Result, 4) = "edit" Then
      oField.Unlink
    End If
  End If
Next
Set oField = Nothing

sample = "[edit]"

Document.Application.Selection.Find.ClearFormatting
Document.Application.Selection.Find.Replacement.ClearFormatting

With Document.Application.Selection.Find
    .Text = sample
    .Replacement.Text = ""
    .Forward = True
    .Wrap = 1
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Execute Replace:=2
End With


End Sub

推荐阅读