【发布时间】:2019-10-28 20:15:47
【问题描述】:
我已经为测试邮件设置了宏并移动它们。但是,如果我得到另一个 excel 文件,另一个工作表名称在哪里,那么我会收到 VBA 错误:subscript out of range。
错误在这一行:Set xlSheet = xlWB.sheets("MySheet1")
Option Explicit
Sub CheckAttachments(olItem As MailItem)
Const strPath As String = "C:\Users\PC2\Documents\Temp_attachs\"
Const strFindText As String = "Completed"
Dim strFilename As String
Dim olAttach As Attachment
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim bXStarted As Boolean
Dim bFound As Boolean
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myDestFolder = myInbox.Folders("MyFolder1")
If olItem.Attachments.Count > 0 Then
For Each olAttach In olItem.Attachments
If Right(LCase(olAttach.FileName), 4) = "xlsx" Then
strFilename = strPath & Format(olItem.ReceivedTime, "yyyymmdd-HHMMSS") & _
Chr(32) & olAttach.FileName
olAttach.SaveAsFile strFilename
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to read the data
Set xlWB = xlApp.workbooks.Open(strFilename)
Set xlSheet = xlWB.sheets("MySheet1")
If FindValue(strFindText, xlSheet) Then
olItem.Move myDestFolder
'MsgBox "Value found in " & strFilename
bFound = True
End If
xlWB.Close 0
If bXStarted Then xlApp.Quit
If Not bFound Then Kill strFilename
'Exit For
End If
Next olAttach
End If
End Sub
如何测试工作表,如果不存在则退出 sub (errorhandling: exit sub)?
【问题讨论】:
-
在你
Set xlSheet = xlWB.sheets("MySheet1")之后,你可以做一个If Not xlSheet is Nothing then...。还要在Set之后移动on error goto 0。 -
如果链接的答案不足以满足您的需求,请告诉我,我将删除重复的投票。 If 显示如何返回一个布尔值,如果为 false 则可以使用该布尔值退出,如果为 true 则继续。只需添加工作簿限定符。
标签: excel vba error-handling