如何在 Outlook 中使用 VBA 打开和读取 txt 文件附件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27741809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I Open and read a txt file attachment using VBA in Outlook?
提问by caezar
I am trying to automate a process where I get an email with an attached file txt
我正在尝试自动化一个过程,在该过程中我收到一封带有附加文件 txt 的电子邮件
I open and I check the date on the second line and saved to a folder with that date in a particular location.
我打开并检查第二行上的日期,并将该日期保存到特定位置的文件夹中。
With this code and a message rule in Outlook I saved the file in the folder where you wish:
使用此代码和 Outlook 中的消息规则,我将文件保存在您希望的文件夹中:
Now the question is:
How to read the second line of txt before saving?
现在的问题是:
如何在保存前读取txt的第二行?
Public Sub SalvarAnexo(Item As MailItem)
Dim Atmt As Attachment
Dim FileName As String
MsgBox "Mensagem Recebida de " & Item.Sender & "!"
For Each Atmt In Item.Attachments
If Right(Atmt.FileName, 3) = "txt" Then
FileName = "C:\temp\" & Format(Item.CreationTime, "yyyymmdd_hhnnss_") & Atmt.FileName
Atmt.SaveAsFile FileName
End If
Next Atmt
End Sub
回答by brettdj
You can use the FileScriptingObject
to grab the second line of the text file like so.
您可以FileScriptingObject
像这样使用来抓取文本文件的第二行。
Public Sub SalvarAnexo(Item)
Dim Atmt As Attachment
Dim FileName As String
Dim objFSO As Object
Dim objFile As Object
Dim strTest As String
MsgBox "Mensagem Recebida de " & Item.Sender & "!"
For Each Atmt In Item.Attachments
If Right$(Atmt.FileName, 3) = "txt" Then
Set objFSO = CreateObject("Scripting.FileSystemObject")
FileName = "C:\temp\" & Format(Item.CreationTime, "yyyymmdd_hhnnss_") & Atmt.FileName
Atmt.SaveAsFile FileName
Set objFile = objFSO.OpenTextFile(FileName, 1)
strTest = objFile.ReadLine
strTest = objFile.ReadLine
objFile.Close
MsgBox "Your date is " & strTest
End If
Next Atmt
End Sub
回答by Eugene Astafiev
The Outlook object model doesn't provide anything for reading attached files on the fly. You need to save the attachment on the disk as a file and then open it for reading the second line. Also you may consider using the low-level code (or any third-party wrapper) - Extended MAPI. It allows to open an attachment as a stream of bytes.
Outlook 对象模型不提供任何用于即时读取附加文件的内容。您需要将附件作为文件保存在磁盘上,然后打开它以阅读第二行。您也可以考虑使用低级代码(或任何第三方包装器) - 扩展 MAPI。它允许以字节流的形式打开附件。