【问题标题】:Copy content of Excel attachment in Outlook VBA without saving the file在 Outlook VBA 中复制 Excel 附件的内容而不保存文件
【发布时间】:2022-07-25 15:32:27
【问题描述】:

我每天收到 50 封带有 Excel 表格的邮件。我想将每个 Excel 工作表的第一行添加到我计算机上现有的 Excel 工作表中。

我知道如何保存电子邮件中的文件,然后访问第一行。我想直接访问它,而不必保存文件。

类似这样的:

Sub Merge_Reports(itm As Outlook.MailItem)

Dim wb_path As String
Dim app_master As Object
Dim wb_master As Object
Dim ws_master As Object
Dim objAtt As Outlook.Attachment
Dim ws_email As Object
Dim content As String

wb_path = "\\swi56prof01\UserData$\heinreca\Documents\Outlook-Dateien\AllData.xlsx"
Set app_master = CreateObject("Excel.Application")
Set wb_master = app_master.Workbooks.Open(wb_path)
Set ws_master = wb_master.Sheets(1)

For Each objAtt In itm.Attachments
  Set ws_email = objAtt.Sheets(1)
  content = ws_email.Cells("A1")
  ws_master.Cells("A1") = content
End Sub

我正在为ws_email = objAtt.Sheets(1) 苦苦挣扎。我得到了错误

对象不支持该属性或方法

我尝试了这个而不是导致错误的行。

Set app_email = CreateObject("Excel.Application")
Set wb_email = app_email.Workbooks.Open(objAtt)
Set ws_email = wb_email.Sheets(1)

我不知道objAtt在数据类型方面是什么以及如何寻址工作表,以便我可以从中复制第一行。

我找到了Copy Contents of Outlook Attachment,我必须先保存文件才能访问它。没有别的办法吗?

【问题讨论】:

  • 我认为如果不保存就无法访问,因为要打开它,需要从电子邮件中提取它(因为电子邮件以特殊方式对文件进行编码,因此需要首先对其进行解码)。然后需要打开文件才能读取数据。因此,即使您在 Outlook 中双击 Excel 文件,它也会将该文件临时保存在临时文件夹中,以便能够打开并显示它。 • 我认为无法绕过以下程序步骤:保存到磁盘、打开、读取、关闭、删除。
  • 好的,我明白了,那我就这样做 - 谢谢!
  • 现在您已经回答了这个“不可回答”的问题,您无法更改它。如果您发布一个描述不可接受的流程特定方面的新问题,您可能会得到解决方案。可能是关于 Excel 一天要打开 50 次。

标签: excel vba outlook


【解决方案1】:

如果不将工作簿保存到磁盘,就无法访​​问它。将附件保存到磁盘后,您可以使用相同的代码:

Set wb_master = app_master.Workbooks.Open(wb_path)
Set ws_master = wb_master.Sheets(1)

其中wb_path 是您保存的附件(Excel 文件)的文件路径。

Attachment.SaveAsFile 方法将附件保存到指定路径。例如:

Sub SaveAttachment() 
 Dim myInspector As Outlook.Inspector
 Dim myItem As Outlook.MailItem 
 Dim myAttachments As Outlook.Attachments 
 Set myInspector = Application.ActiveInspector 
 If Not TypeName(myInspector) = "Nothing" Then 
   If TypeName(myInspector.CurrentItem) = "MailItem" Then 
     Set myItem = myInspector.CurrentItem 
     Set myAttachments = myItem.Attachments 
     'Prompt the user for confirmation 
     Dim strPrompt As String 
     strPrompt = "Are you sure you want to save the first attachment in the current item to the Documents folder? If a file with the same name already exists in the destination folder, it will be overwritten with this copy of the file." 
     If MsgBox(strPrompt, vbYesNo + vbQuestion) = vbYes Then 
       myAttachments.Item(1).SaveAsFile Environ("HOMEPATH") & "\My Documents\" & _ 
       myAttachments.Item(1).DisplayName 
     End If 
   Else 
     MsgBox "The item is of the wrong type." 
   End If 
 End If 
End Sub

【讨论】:

    猜你喜欢
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    相关资源
    最近更新 更多