我得到编译错误: – 子或function没有在Excel中定义! 请注意,“工具”选项卡中的引用未激活

Private Sub CommandButton1_Click() send email End Sub Public Function sendmail() On Error GoTo ende esubject = "Systematic and Manually Created ASN" sendto = "oo@hp.com" ccto = "rt@hp.com" ebody = "Hello All" & vbCrLf & _ "Please find the Systematically and Manually created ASN for the last month" & _ vbCrLf & "With Regards" & vbCrLf & "Tarak" newfilename = "C:\Stuff.XLS" Set apps = CreateObject("Outlook.Application") Set itm = app.createitem(0) With itm .Subject = esubject .to = sendto .cc = ccto .body = ebody .attachments.Add (newfilename) .display .Send End With Set app = Nothing Set itm = Nothing ende: End Function 

编辑:

哎呀,我误解你的子名。

你应该把它添加到你的模块的顶部,以帮助你在将来。

 Option Explicit 

这个更新的build议实际运行。

您的代码:Private Sub CommandButton1_Click()发送电子邮件结束小组

应该读:

 Private Sub CommandButton1_Click() sendmail End Sub 

请注意从发送电子邮件到sendmail的更改。

另外:

 Set apps = CreateObject("Outlook.Application") Set itm = app.createitem(0) 

应该读

 Set apps = CreateObject("Outlook.Application") Set itm = apps.createitem(0) 

注意丢失的s。 如果没有这样的话,代码将会在错误之后立即出错。

编辑2:

也许向你展示我的意思更容易。 当你使用显式选项时,你必须显式声明你的variables。 亲是你将无法使用你没有声明的variables,这将阻止你使用应用程序,当你的意思是应用程序例如。

这里是你的脚本的更正版本:

 Option Explicit Private Sub CommandButton1_Click() sendmail End Sub Public Function sendmail() On Error GoTo ende Dim esubject As String, sendto As String, ccto As String, ebody As String, newfilename As String Dim apps As Object, itm As Object esubject = "Systematic and Manually Created ASN" sendto = "oo@hp.com" ccto = "rt@hp.com" ebody = "Hello All" & vbCrLf & _ "Please find the Systematically and Manually created ASN for the last month" & _ vbCrLf & "With Regards" & vbCrLf & "Tarak" newfilename = "C:\Stuff.XLS" Set apps = CreateObject("Outlook.Application") Set itm = apps.createitem(0) With itm .Subject = esubject .To = sendto .cc = ccto .body = ebody .attachments.Add (newfilename) .display .Send End With Set apps = Nothing Set itm = Nothing ende: End Function