通过电子邮件发送Excel / Outlook中的选定范围

时间:2015-05-21 19:58:06

标签: excel vba excel-vba outlook-vba automated-deployment

我有以下代码(由Ron de Bruin提供),我正在试图找出如何自定义它以供我自己使用。

当我运行代码时,没有任何反应(因为错误处理程序在错误“下标超出范围”时停止宏),

但是当我更改这一行时:

ActiveWorkbook.EnvelopeVisible = False

为:

ActiveWorkbook.EnvelopeVisible = True

可见信封允许我进行选择并选择我要发送给谁等。

我想知道它为什么会遇到“超出范围”的错误,并且如果有可能让这个过程自动完成而不需要我在事件触发后输入内容[它正在从Workbook_Open中触发( )事件 - 如果这有任何区别,并且在同一工作簿中的另一个工作表(工作表(“ValLog”))中进行选择]

我正在运行的代码是:

Private Sub workbook_open()

Dim AWorksheet As Worksheet
Dim Sendrng, rng As Range
Dim answer As Integer

On Error GoTo StopMacro

answer = MsgBox("Do you want to send e-mail notifications of upcoming tours?", vbYesNo)

If answer = vbYes Then

With Application
    .ScreenUpdating = False
    .EnableEvents = False
End With

Set Sendrng = Worksheets("ValLog").Range("B5:K12").Select

With Sendrng

    'Select the range you want to mail
    Range("B5:K12").Select

    ' Create the mail and send it
    ActiveWorkbook.EnvelopeVisible = True
    With .Parent.MailEnvelope

        .Introduction = "Test Test Test"

        With .Item
            .To = "myemail@blahblah.com"
            .CC = ""
            .BCC = ""
            .Subject = "Why, Error?"
            .Send
        End With

    End With

StopMacro:
With Application
    .ScreenUpdating = True
    .EnableEvents = True
End With
ActiveWorkbook.EnvelopeVisible = False

End With

Else
'Do Nothing
End If

End Sub

1 个答案:

答案 0 :(得分:2)

首先,您尚未将SendRange声明为范围。这一行:

Dim SendRange, rng As Range

声明SendRange作为变体和rng作为范围。将其更改为:

Dim SendRange As Range, rng As Range

其次,改变这一行:

Set Sendrng = Worksheets("ValLog").Range("B5:K12").Select

为:

Set Sendrng = Worksheets("ValLog").Range("B5:K12")

您正尝试在此处设置范围,而不是选择它。

然后,改变:

Range("B5:K12").Select

为:

.Select

您在代码中实际执行的操作是在活动表中选择范围(因为您没有在范围之前定义工作表)。把它放在" With"声明,每个声明都带有"。"在它将从with语句继承该术语之前。因此用"。选择"你实际上正在运行" Sendrng.Select"