Outlook VBA调用Excel宏

时间:2016-09-15 15:52:39

标签: excel vba excel-vba outlook outlook-vba

我有一个Outlook宏来处理电子邮件并将其粘贴到Excel中,然后调用Excel宏进行进一步处理。单独调用时,两个宏按预期工作。但是,如果我尝试从Outlook宏调用Excel宏,则电子邮件将粘贴到Excel工作簿中,然后在调用Excel宏时会生成错误,因为没有数据。知道为什么

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

会导致数据无法从Outlook粘贴到Excel中吗?仅当存在此行代码时才会出现此错误。提前谢谢!

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

2 个答案:

答案 0 :(得分:3)

user2676140的建议有效。我将睡眠时间改为15秒,这就完成了。谢谢!

答案 1 :(得分:1)

如果您想要从剪贴板中删除格式化文本,则无法使用xlPasteValues。请改用:

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

注意,这会将内容粘贴为纯文本。如果您需要格式化,可以将Format参数更改为"HTML"