记事本中的VBA在Excel中运行代码错误

时间:2012-12-13 20:15:21

标签: excel vba excel-vba

这是我在记事本中保存的代码。我是否需要更改Excel.Applications?

Option Explicit

Dim xlApp
Dim xlBook

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("H:\shane.xlsm", 0, True)

xlApp.Run "Email"
xlBook.close
xlApp.Quit

Set xlBook = Nothing
Set xlApp = nothing

这是我发送电子邮件的代码,当我测试它时工作正常并会给我发电子邮件。

Option Explicit

Const strTo As String = "dvandervieren@enerplus.com"
Const strCC As String = ""  '<~~ change "def@abc.com" to "" if you do not want to CC
Const strBCC As String = "" '<~~ change "ghi@abc.com" to "" if you do not want to BCC

Sub Email()
Dim OutApp As Object, OutMail As Object
Dim strbody As String, strSubject As String

strSubject = "Hello World"
strbody = "This is the message for the body"

Set OutApp = CreateObject("Outlook.Application")

Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
    .To = strTo
    .CC = strCC
    .BCC = strBCC
    .Subject = "This is the Subject line"
    .Body = strbody
    .Send
End With
On Error GoTo 0

Set OutMail = Nothing
Set OutApp = Nothing
End Sub

1 个答案:

答案 0 :(得分:0)

打开您的Excel文档。打开VB编辑器。在左侧窗格中找到excel文档。右键单击并选择“插入”&gt;&gt;“模块”。将代码移动到新创建的模块中。然后,您应该只使用方法名称Email来调用它。您不需要对excel应用程序进行delcare,因为您已经在excel中。 - Sorceri