我试图在Excel和Outlook中编写一些宏,最后将自动解压缩并打开CSV,处理数据,然后在新电子邮件到达特定文件夹时将其发送到需要的地方。我已经在Excel方面完成了所有工作,但是在使用Outlook时遇到了困难。下面的代码将文件解压缩。我将如何打开解压缩的文件并触发Excel宏(该宏始终在另一个工作簿中打开)?
我遇到的另一个问题:该代码仅在我实际在其自己的窗口中打开目标电子邮件时才起作用。
Public Sub OpenZippedSheet()
Dim objMail As Outlook.MailItem
Dim objAttachments As Outlook.Attachments
Dim objAttachment As Outlook.Attachment
Dim objShell As Object
Dim objFileSystem As Object
Dim strTempFolder As String
Dim strFilePath As String
Dim strFileName As String
Set objMail = Outlook.Application.ActiveInspector.CurrentItem
Set objAttachments = objMail.Attachments
'Save & Unzip the zip file in local drive
Set objShell = CreateObject("Shell.Application")
Set objFileSystem = CreateObject("Scripting.FileSystemObject")
strTempFolder = objFileSystem.GetSpecialFolder(2).Path & "\Temp" & Format(Now, "yyyy-mm-dd-hh-mm-ss")
MkDir (strTempFolder)
For Each objAttachment In objAttachments
If Right(objAttachment.FileName, 3) = "zip" Then
strFilePath = strTempFolder & "\" & objAttachment.FileName
objAttachment.SaveAsFile (strFilePath)
objShell.NameSpace((strTempFolder)).CopyHere objShell.NameSpace((strFilePath)).Items
End If
Next
End Sub
我假设我会做某种object.open,但是我不知道要使其在Excel中实际打开的语法是什么。然后有没有办法从Outlook触发Excel宏?
非常感谢!
答案 0 :(得分:0)
仅当我实际上在其自己的窗口中打开目标电子邮件时,此代码才似乎起作用。
那是因为您依赖ActiveInspector
窗口。如果要处理在“资源管理器”窗口中选择的项目,则需要检查Selection
对象(请参见相应的属性)。
要打开Excel文件,您可以:
要从其他应用程序运行VBA宏代码,可以使用Application.Run
方法。在How do I use Application.Run in Excel文章中了解有关此内容的更多信息。
Application.Run "'" & TestWkbk.Name & "'!MacroNameHere", "parm1", "parm2"
答案 1 :(得分:0)
类似的事情(未经测试,可能需要一些修复):
'Note - any paths passed to objShell should be
' passed as *Variants*, not Strings
Dim oXL As Object, wbCSV As Object, fileNameInZip As Variant
Set objShell = CreateObject("Shell.Application")
For Each objAttachment In objAttachments
If Right(objAttachment.Filename, 3) = "zip" Then
strFilePath = strTempFolder & "\" & objAttachment.Filename
objAttachment.SaveAsFile strFilePath
Set oNS = oApp.Namespace(strFilePath)
For Each fileNameInZip In oNS.items 'loop over the files in the zip
Debug.Print fileNameInZip
If LCase(fileNameInZip) Like "*.csv" Then 'csv file?
'extract the file
objShell.Namespace(strTempFolder).copyhere oNS.items.Item(CStr(fileNameInZip))
If oXL Is Nothing Then Set oXL = GetObject(, "Excel.Application") 'assumes excel is running
Set wbCSV = oXL.Workbooks.Open(strTempFolder & "\" & fileNameInZip)
oXL.Run "'YourMacroFile.xlsm'!YourMacroName" 'run the macro
'clean up stuff...
End If 'is a csv file
Next 'file in zip
End If 'attachment is a zip file
Next 'attachment