【发布时间】:2020-03-24 23:41:15
【问题描述】:
我正在尝试在 Excel VBA 中部署一个程序来发送邮件、复制和粘贴 Word 文档中的文本。
我的程序运行,但在某个时候它会抛出错误,我看到有很多 Word 应用程序打开,所以我必须使用任务管理器关闭它们。我尝试使用Object.Quit 函数将对象设置为Nothing。
我认为程序的随机错误的根源在于我的计算机内存使用不当。我不知道如何使用计算机中的内存,因为我的背景与编程无关。
Sub CustomizedMail()
Dim wd As Object, editor As Object
Dim outlookApp As Outlook.Application
Dim mymail As Outlook.MailItem
Dim doc As Object
Dim generalDirectory As String
Dim document As String
Dim ActiveRow As Integer
Dim mailType As String
Break = Chr(13) + Chr(10)
'Selects address of letters to Clients
generalDirectory = "C:\Users\Rodrigo\OneDrive - InBody Co., Ltd\Ventas Rod\Forecast\Ppts informativas x área\Para enviar\"
'Selects document to be sent according to ppt type value in worksheet
ActiveRow = ActiveCell.Row
mailType = ActiveCell.Worksheet.Range("O" & ActiveRow).Value
'Check mailType
If mailType = "" Then
MsgBox "Selecciona un tipo de mail"
Exit Sub
End If
'Opens word document and copies its information
document = generalDirectory & mailType & ".docx"
Set wd = CreateObject("Word.Application")
Set doc = wd.documents.Open(document)
'wd.Visible = True
doc.Content.Copy
doc.Close
'Set wd = Nothing
'Opens Outlook and paste
Set outlookApp = New Outlook.Application
'CreateObject("Outlook.Application") 'New Outlook.Application
Set mymail = outlookApp.CreateItem(olMailItem)
With mymail
On Error GoTo 1
.To = ActiveCell.Worksheet.Range("N" & ActiveRow)
If mailType = "Presentación" Then
.Subject = "Bioimpedanciómetros profesionales InBody"
Else
.Subject = "Bioimpedanciómetros para " & mailType
End If
'.BodyFormat = olFormatRichText
Set editor = .GetInspector.WordEditor
editor.Content.Paste
'editor.Quit
Set editor = Nothing
.Display
End With
'Append corresponding file
sourceFile = generalDirectory & "INBODY - " & mailType & ".pdf"
mymail.Attachments.Add sourceFile
ActiveCell.Worksheet.Range("T" & ActiveRow).Value = "Yes"
ActiveCell.Worksheet.Range("V" & ActiveRow).Value = Date
'MsgBox ThisWorkbook.FullName
'MsgBox ThisWorkbook.Path
Exit Sub
1: MsgBox "Excel se puso pendejo, intenta de nuevo"
End Sub
【问题讨论】:
-
在您的代码中,您没有
wd.Quit和Set wd = Nothing被注释掉。这是故意的吗? -
Set wd = CreateObject("Word.Application")将在每次运行时创建一个新的 Word 实例。您应该做的是在Set wd = Word.Application之前使用On Error Resume Next并仅在发生错误时创建新实例(意味着没有加载的Word 实例)。Wd.Quit似乎没有效果的可能原因是因为您打开了太多实例,以至于关闭一个实例没有任何区别。对 Outlook 应用程序的处理也是如此。 -
感谢您的回答,.Quit 和 wd = 没有任何评论,因为我进行了实验以查看它们是否有效,并且由于它们似乎在我的代码中不起作用,所以我让他们评论。我将尝试 On Error Resume Next。你知道为什么会发生错误吗?我认为计算机错误是代码问题的主要原因,我应该怎么做才能避免此类错误?