【问题标题】:Outlook VBA Calling an Excel MacroOutlook VBA 调用 Excel 宏
【发布时间】:2020-06-24 20:56:02
【问题描述】:

我有一个 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

【问题讨论】:

  • 我看到您在代码中使用了“睡眠”,您的睡眠时间是否足以粘贴电子邮件?
  • 好的——看来这不是解决办法。我收到此代码的间歇性运行时 91 错误。有时代码工作正常,有时却不行。有什么想法吗?
  • 您可以在您的问题上添加您的 xlsb 代码吗?

标签: excel vba outlook


【解决方案1】:

user2676140 的建议奏效了。我将睡眠时间更改为 15 秒,这样就成功了。谢谢!

【讨论】:

    【解决方案2】:

    如果您想从剪贴板粘贴格式化文本,则不能使用xlPasteValues。改用这个:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多