方法' ThisWorkbook'对象' _Global'失败

时间:2015-09-30 11:55:22

标签: vba excel-vba outlook-vba excel

我试图将邮件主题,sendername,电子邮件的日期从PST邮箱复制到Excel工作簿。 这是我到目前为止的代码:

Option Explicit
Sub Download_Outlook_Mail_To_Excel()
Dim Folder As Outlook.MAPIFolder
Dim sFolders As Outlook.MAPIFolder
Dim iRow As Integer, oRow As Integer
Dim MailBoxName As String, Pst_Folder_Name  As String


MailBoxName = "Backupmailbox"


Pst_Folder_Name = "Inbox1" 'Sample "Inbox" or "Sent Items"

'To directly a Folder at a high level
'Set Folder = Outlook.Session.Folders(MailBoxName).Folders(Pst_Folder_Name)

'To access a main folder or a subfolder (level-1)
For Each Folder In Outlook.Session.Folders(MailBoxName).Folders
    If VBA.UCase(Folder.Name) = VBA.UCase(Pst_Folder_Name) Then GoTo Label_Folder_Found
    For Each sFolders In Folder.Folders
        If VBA.UCase(sFolders.Name) = VBA.UCase(Pst_Folder_Name) Then
            Set Folder = sFolders
            GoTo Label_Folder_Found
        End If
    Next sFolders
Next Folder

Label_Folder_Found:
 If Folder.Name = "" Then
    MsgBox "Invalid Data in Input"
    GoTo End_Lbl1:
End If

'Read Through each Mail and export the details to Excel for Email Archival
ThisWorkbook.Sheets(1).Activate
Folder.Items.Sort "Received"

'Insert Column Headers
ThisWorkbook.Sheets(1).Cells(1, 1) = "Sender"
ThisWorkbook.Sheets(1).Cells(1, 2) = "Subject"
ThisWorkbook.Sheets(1).Cells(1, 3) = "Date"
ThisWorkbook.Sheets(1).Cells(1, 4) = "Size"
ThisWorkbook.Sheets(1).Cells(1, 5) = "EmailID"
'ThisWorkbook.Sheets(1).Cells(1, 6) = "Body"

'Export eMail Data from PST Folder
oRow = 1
For iRow = 1 To Folder.Items.Count
    'If condition to import mails received in last 60 days
    'To import all emails, comment or remove this IF condition
    If VBA.DateValue(VBA.Now) - VBA.DateValue(Folder.Items.Item(iRow).ReceivedTime) <= 60 Then
       oRow = oRow + 1
       ThisWorkbook.Sheets(1).Cells(oRow, 1).Select
       ThisWorkbook.Sheets(1).Cells(oRow, 1) = Folder.Items.Item(iRow).SenderName
       ThisWorkbook.Sheets(1).Cells(oRow, 2) = Folder.Items.Item(iRow).Subject
       ThisWorkbook.Sheets(1).Cells(oRow, 3) = Folder.Items.Item(iRow).ReceivedTime
       ThisWorkbook.Sheets(1).Cells(oRow, 4) = Folder.Items.Item(iRow).Size
       ThisWorkbook.Sheets(1).Cells(oRow, 5) = Folder.Items.Item(iRow).SenderEmailAddress
       'ThisWorkbook.Sheets(1).Cells(oRow, 6) = Folder.Items.Item(iRow).Body
    End If
Next iRow
MsgBox "Outlook Mails Extracted to Excel"
Set Folder = Nothing
Set sFolders = Nothing

End_Lbl1:
End Sub

当我运行代码时,我得到了

  

&#34;对象范围的方法_全局失败&#34;

来自声明ThisWorkbook.Sheets(1).Activate

我启用了Microsoft Excel 14.0对象库引用,因为代码是从Outlook应用程序执行的。

有谁知道这个错误意味着什么,我该如何解决?

1 个答案:

答案 0 :(得分:0)

只需几次快速调整,试试这个:

String cate = category.getValue().toString();

这将为您打开工作簿,因此无需事先做到