1

我有以下代码(由Ron de Bruin提供)并试图弄清楚如何自定义它以供我自己使用。

当我运行代码时,什么也没有发生(因为错误处理程序在错误“下标超出范围”时停止宏),

但是,当我换行时:

ActiveWorkbook.EnvelopeVisible = False

至:

ActiveWorkbook.EnvelopeVisible = True

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

我想知道为什么它会遇到“超出范围”错误,以及是否可以在事件触发后自动完成该过程而无需我输入内容[它是从 Workbook_Open() 事件中触发的-如果这有什么不同,并且选择是在同一工作簿中的另一个工作表(Worksheet(“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
4

1 回答 1

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 语句继承术语之前。因此,使用“.Select”,您实际上正在运行“Sendrng.Select”

于 2015-05-21T20:19:17.147 回答