gpt4 book ai didi

vba - Excel VBA : Sent Outlook email does not include pasted Range

转载 作者:行者123 更新时间:2023-12-02 10:13:30 25 4
gpt4 key购买 nike

我有initially answered问题How to only paste visible cells in an email body

我测试和发布的代码(见下文)不包括发送电子邮件。在OP将其添加到他的问题后,我添加了 .Send 部分,但我获得的行为非常奇怪。如果我在发送之前放置一个断点,并执行 Sub,则会创建一封包含正确信息的电子邮件(包括粘贴的 Excel Range)。然后我继续执行并且电子邮件被正确发送。但是,如果我立即运行整个 Sub(没有断点),则发送的电子邮件正文中不会粘贴 Excel Range

这是什么原因,解决办法是什么?

我尝试注释/取消注释最后两行(Set ... = Nothing),但没有帮助。

<小时/>

相关问题:

Copy range of cells from Excel to body of email in Outlook

Pasting formatted Excel range into Outlook message

<小时/>

引用代码(基于 Ron de Bruin 的典型代码,请参阅 thisthis):

Sub SendEmail()

Dim OutlookApp As Object
'Dim OutlookApp As Outlook.Application
Dim MItem As Object
'Dim MItem As Outlook.MailItem

'Create Outlook object
Set OutlookApp = CreateObject("Outlook.Application")
'Set OutlookApp = New Outlook.Application

Dim Sendrng As Range
Set Sendrng = Worksheets("Test").Range("A1").SpecialCells(xlCellTypeVisible)
Sendrng.Copy

'Create Mail Item
Set MItem = OutlookApp.CreateItem(0)
'Set MItem = OutlookApp.CreateItem(olMailItem)
With MItem
.To = "test@email.com"
.To = "SSEREBRINSKY@TENARIS.COM"
.Subject = "Test"
.CC = ""
.BCC = ""
'.Body = "a"
.Display
End With
SendKeys "^({v})", True
With MItem
.Send
End With

'Set OutlookApp = Nothing
'Set MItem = Nothing

End Sub

最佳答案

But if I run the whole Sub at once, with no breakpoints, the email is sent with no pasted Excel Range in the body. What is the reason for that, and what is the solution?

原因很简单。当您使用断点时,您为 Excel 提供了足够的时间来进行复制粘贴。 SendKeys因此在与其他应用程序一起使用时非常不可靠。

有很多方法可以解决您的问题。一是给复制粘贴足够的时间。您可以使用 DoEvents 来做到这一点或强制 Wait Time 。例如

SendKeys "^({v})", True
DoEvents

或者

SendKeys "^({v})", True
Wait 2 '<~~ Wait for 2 seconds

并在您的代码中使用此子

Private Sub Wait(ByVal nSec As Long)
nSec = nSec + Timer
While nSec > Timer
DoEvents
Wend
End Sub

顺便说一句,而不是使用 SendKeys您可以使用RangetoHTML Ron de Bruin 的函数,如图 HERE

编辑

如果以上不起作用,则意味着 SendKeys在这种情况下执行得太快,请使用 DoEvents/Wait就在.Display之后也是如此。

.Display
DoEvents

或者

.Display
Wait 2

关于vba - Excel VBA : Sent Outlook email does not include pasted Range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20963032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com