私はoutlookで電子メールのリストから添付ファイルをダウンロードするために使用している以下のコードを使用しています。オブジェクト変数またはブロック変数が設定されていませんforループの2番目の反復でエラーが発生しました
コードはループの最初の繰り返しで正常に動作しますが、2番目の繰り返しでは、ファイルをデスクトップの一時フォルダ(つまり、wb.SaveAs FileFormat:=51, FileName:=xlNameAndPath
)に保存しようとしている段階でRun-time error '91' Object variable or With block variable not set
というエラーが発生します。
ドキュメントhereといくつかのテストを読んでから、その後、2回目の反復でエラーが発生何にwb
を設定し、問題が実際にwb.close
により、ループの最初の反復で引き起こされているようです。
私は間違いなく、私の質問は、 "オブジェクト変数の参照を再指定する"方法ですか?
Sub SaveExcels()
Dim objNS As Outlook.NameSpace: Set objNS = GetNamespace("MAPI")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = objNS.GetDefaultFolder(olFolderInbox)
Dim Item As Object
Dim objAttachments As Outlook.Attachments
For Each Item In olFolder.Items
If TypeOf Item Is Outlook.MailItem Then
Dim oMail As Outlook.MailItem: Set oMail = Item
' Check it contains an attachment
Set objAttachments = oMail.Attachments
lngCount = objAttachments.Count
' Check its from the right company
senderCheck = InStr(oMail.SenderEmailAddress, "company.com")
' Check that it is the right email type
subjectCheck = InStr(oMail.Subject, "TYPE")
' Check whether its the latest weeks data
receivedDate = DateValue(oMail.ReceivedTime)
todaysDate = DateValue(Now())
dateDifference = todaysDate - receivedDate
If lngCount > 0 And senderCheck > 0 And subjectCheck > 0 And dateDifference <= 7 Then
' Get the file name
strFile = objAttachments.Item(1).FileName
' Debug.Print strFile
strFolderpath = "D:\Users\" & Environ("Username") & "\Desktop\temp\"
' Combine with the path to the Temp folder.
strFileIncPath = strFolderpath & strFile
' Debug.Print strFile
' Save the attachment as a file.
objAttachments.Item(1).SaveAsFile strFileIncPath
' Extract the files into the newly created folder
Set oApp = CreateObject("Shell.Application")
oApp.NameSpace(strFolderpath).CopyHere oApp.NameSpace(strFileIncPath).Items
' Delete the zip file
Kill strFileIncPath
' Open the excel file
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Application.Visible = True
xlName = Replace(strFile, ".ZIP", "")
xlNameTemp = xlName & "_00000.xls"
xlNameAndPath = strFolderpath & xlName
Debug.Print xlNameAndPath
xlApp.Workbooks.Open strFolderpath & xlNameTemp
Dim wb As Workbook
Set wb = ActiveWorkbook
' Save as unique name and close
wb.SaveAs FileFormat:=51, FileName:=xlNameAndPath << ERROR
' Get rid of the old excel
Kill strFolderpath & xlNameTemp
' Close the workbook
wb.Close
End If
End If
Next
End Sub
"Set wb = ActiveWorkbook"では、デバッガを使ってActiveWorkbookが有効かどうかを確認できますか? (最初に定義されたActiveWorkbookはどこですか?) –
@SandyGettings私はSamがタイプライブラリ「Microsoft Excelオブジェクトライブラリ」(VBA Editor、Tools | References)への参照を追加したと仮定します。これにより 'Dim 'ステートメントで' Workbook'と同様の型が見えるようになります。また、 'ActiveWorkbook'グローバルと' ActiveSheet'と 'xl *'定数を提供します。 –
cxw