如何使用Word设计的宏在Outlook中运行?

时间:2018-12-09 17:27:07

标签: vba outlook ms-word

对编码而言相对较新,因此,感谢您能给我的任何帮助。

我在Word中编写了一段代码,以查找文档中的“ [edit]”链接,断开超链接,然后删除文本。它在Word中完美地工作,我想修改此宏使其在Outlook中运行。我进入了tools> references以允许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电子邮件的文本?

谢谢您的帮助,

1 个答案:

答案 0 :(得分:-1)

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

  • 您在其中引用ActiveDocument,因为它是Outlook对象集合的一部分。并非如此,因此您需要引用从检查器正确创建的Document对象。选择也一样。
  • 我使用了后期绑定(Dim oField As Object),不确定使用早期绑定和“ tools> references”选项是否也遇到了这种麻烦,但是无法识别单词常量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