简体   繁体   English

Outlook VBA 调用 Excel 宏

[英]Outlook VBA Calling an Excel Macro

I have an Outlook macro which processes an email and pastes it into Excel, and then calls an Excel macro for further processing.我有一个 Outlook 宏,它处理电子邮件并将其粘贴到 Excel 中,然后调用 Excel 宏进行进一步处理。 When called separately, the two macros work as expected.单独调用时,这两个宏按预期工作。 However, if I try to call the Excel macro from the Outlook macro, the email will not paste into the Excel workbook, and then when the Excel macro is called it generates an error because there is no data.但是,如果我尝试从 Outlook 宏调用 Excel 宏,则电子邮件不会粘贴到 Excel 工作簿中,然后在调用 Excel 宏时会生成错误,因为没有数据。 Any idea why知道为什么

    xlApp.Run ("PERSONAL.XLSB!Commissions_Report_Format")

would cause the data to not paste from Outlook into Excel?会导致数据无法从 Outlook 粘贴到 Excel 中吗? The error only occurs when this line of code is present.仅当存在这行代码时才会发生错误。 Thanks in advance!提前致谢!

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Option Explicit

Sub PasteToExcel(item As Outlook.MailItem)
Dim activeMailMessage As MailItem
Dim xlApp As Excel.Application
Dim Wb As Excel.Workbook
Dim Ws As Excel.Worksheet

    'Get a handle on the email
    Set activeMailMessage = ActiveExplorer.Selection.item(1)

    'Copy the formatted text:
    activeMailMessage.GetInspector().WordEditor.Range.FormattedText.Copy  

    'Ensure Excel Application is open
    Set xlApp = CreateObject("Excel.Application")

    'Make Excel Application visible
    xlApp.Visible = True

    'Open the Personal Macro Workbook, or the Excel macro won't run
    xlApp.Workbooks.Open ("C:\Users\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.xlsb")

    'Name the Excel File
    Set Wb = xlApp.Workbooks.Add

    'Paste the email
    Set Ws = xlApp.Sheets(1)
    Ws.Activate
    Ws.Range("A1").Select
    Sleep 3000
    Selection.PasteSpecial xlPasteValues
    Sleep 3000 'wait for 3 seconds

    'Run the Excel macro to clean up the file
    xlApp.Run ("PERSONAL.XLSB!Commissions_Report_Format")

End Sub

user2676140's suggestion worked. user2676140 的建议有效。 I changed the sleep time to 15 seconds, and that has done the trick.我将睡眠时间更改为 15 秒,这就成功了。 Thanks!谢谢!

You can't use xlPasteValues if you want to past formatted text from the clipboard.如果要从剪贴板粘贴格式化文本,则不能使用xlPasteValues Use this instead:改用这个:

Selection.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:=False

Note, that will paste the content as plain text.请注意,这会将内容粘贴为纯文本。 If you need formatting, you can change the Format parameter to "HTML" .如果需要格式化,可以将Format参数更改为"HTML"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM