【问题标题】:Setting Range based on Selection根据选择设置范围
【发布时间】:2019-10-25 10:37:44
【问题描述】:

我想在电子邮件中使用参考号来突出显示并替换为网页的直接链接。

当前代码会将新的超链接放置在电子邮件的开头而不是所选区域(当前为wddoc.Range(0 , 0))。

如果我使用Selection,则表示该变量未由用户定义。

Sub AddHyperlink()
Dim olEmail As Outlook.MailItem
Dim olInsp As Outlook.Inspector
Dim wdDoc As Object
Dim oLink As Object
Dim oRng As Object
Dim strLink As String
Dim strLinkText As String
Dim OutApp As Object
Dim OutMail As Object
Dim strText As String

On Error Resume Next
'Get Outlook if it's running
Set OutApp = GetObject(, "Outlook.Application")

'Outlook wasn't running, so cancel
If Err <> 0 Then
    MsgBox "Outlook is not running so nothing can be selected!"
    GoTo lbl_Exit
End If

On Error GoTo 0

Set OutMail = OutApp.ActiveExplorer.Selection.Item(1)

With OutMail
    Set olInsp = .GetInspector
    Set wdDoc = olInsp.WordEditor
    strText = wdDoc.Application.Selection.Range.Text
End With

strLink = "http://website.com/#" & strText & "" ' the link address
strLinkText = "" & strText & "" ' the link display text

On Error Resume Next
Set olEmail = ActiveInspector.CurrentItem

With olEmail
    .BodyFormat = olFormatHTML
    Set olInsp = .GetInspector
    Set wdDoc = olInsp.WordEditor
    Set oRng = wdDoc.Range(0, 0) '!!!Cannot find something that replaces range with current selection!!!!
    oRng.Collapse 0
    Set oLink = wdDoc.Hyperlinks.Add(Anchor:=oRng, _
                         Address:=strLink, _
                         SubAddress:="", _
                         ScreenTip:="", _
                         TextToDisplay:=strLinkText)

    Set oRng = oLink.Range
    oRng.Collapse 0
    .Display
End With

lbl_Exit:
    Exit Sub

End Sub

当我在 MS Outlook 中打开一封新电子邮件时,我将设置一个键盘快捷键,以便在 Outlook 中运行 VBA 中的代码。

【问题讨论】:

  • 你从哪里运行代码?
  • 当我在 ms Outlook 中打开一封新电子邮件时,我将设置一个键盘 shortcut 设置以在 Outlook 中运行 VBA 中的代码。

标签: vba hyperlink outlook


【解决方案1】:

使用ActiveInspector 时的 Outlook vba,请尝试以下操作。

Option Explicit
Public Sub Example()
    Dim wdDoc As Word.Document
    Dim rngSel As Word.selection

    If Application.ActiveInspector.EditorType = olEditorWord Then
        Set wdDoc = Application.ActiveInspector.WordEditor ' use WordEditor
        Set rngSel = wdDoc.Windows(1).selection ' Current selection

        wdDoc.Hyperlinks.Add rngSel.Range, _
        Address:="U:\plot.log", TextToDisplay:="Here is the link"
    End If

    Set wdDoc = Nothing
End Sub

【讨论】:

  • 这将替换第一个'end with'之后的所有内容?
  • @dripdrop 这是完整的代码,试一试-告诉我
  • 更改了 word.document 和 word.selection,因为它们给我的 outlook.inspector 和 outlook.selection 带来了错误。现在我在“使用 WordEditor”时遇到不匹配错误。
猜你喜欢
  • 2017-01-11
  • 2018-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-14
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多