2017-05-02 126 views
1

我有大約90。味精,我需要打開Outlook文件,轉換成Excel附件爲.csv文件,並保存了。目前,下面的代碼是簡單地打開.msg展望文件,但出現錯誤:enter image description here無法打開.msg文件

如何允許打開.msg文件。

腳本:

Sub OpenMSGRenameDownloadAttachement() 

    Dim objOL As Outlook.Application 
    Dim Msg As Outlook.MailItem 

    Dim MsgCount As Integer 

    Set objOL = CreateObject("Outlook.Application") 

    'Change the path given month, ie. do this for Jan, Feb, April 
    inPath = "C:\January Messages" 

    thisFile = LCase(Dir(inPath & "\*.msg")) 
    Do While thisFile <> "" 

     Set Msg = objOL.Session.OpenSharedItem(thisFile) 

     Msg.Display 

     MsgBox Msg.Subject 
     thisFile = Dir 
    Loop 

    Set objOL = Nothing 
    Set Msg = Nothing 

End Sub 
+1

我想這是一個明顯的問題,但該文件已經打開?例如。在Outlook中?或者在Excel中,您的代碼在早期嘗試失敗?或從以前的成功嘗試在Excel中? (它看起來並不像您明確正在執行「Close」,因此它可能仍然是開放的。)此外,此頁面是否適用:https://support.microsoft.com/zh-cn/help/2633737/the -openshareditem-method-for-outlook-holds-a-file-handle-on-signed-.msg-files – YowE3K

+0

這是一次性的事情。我如何重寫這個工作,至少打開郵件,我可以從那裏轉換excel。 – Sauron

+0

您正在使用Dir錯誤。嘗試使用'thisFile = Dir(inPath)'並在'Do While thisFile <>「」'後放置一個If條件'如果Right(thisFile,3)=「msg」Then'',並且不需要物理地打開消息據我所知,獲得附件。 – Tehscript

回答

5

試試這個:

Sub OpenMSGRenameDownloadAttachement() 
Dim Msg As Outlook.MailItem 
Dim objAtt As Outlook.Attachment 
Set objOL = CreateObject("Outlook.Application") 
Set objNs = objOL.GetNamespace("MAPI") 
'objNs.Logon 

inPath = "C:\January Messages\" 
outPath = "C:\January Messages\attachments\" 'create this folder for attachments or use your own 
thisFile = Dir(inPath & "*.msg") 

Do While Len(thisFile) > 0 
    Set Msg = objNs.OpenSharedItem(inPath & thisFile) 
    'MsgBox inPath & thisFile 
    'MsgBox Msg.Subject 
    'MsgBox Msg.SenderEmailAddress 
    'MsgBox Msg.Recipients.Item(1).Address 
    For Each objAtt In Msg.Attachments 
     If Right(objAtt, 4) = "xlsx" Or Right(objAtt, 3) = "xls" Then 
      objAtt.SaveAsFile outPath & Split(objAtt.DisplayName, ".")(0) & ".csv" 
     End If 
    Next 
    thisFile = Dir 
Loop 

Set objOL = Nothing 
Set objNs = Nothing 
End Sub 
+0

這不起作用,運行 – Sauron

+0

變化'Debug.Print'時'Msgbox' – Tehscript

+0

這也不起作用 – Sauron