[英]Excel VBA - when looping through files in a directory, how to skip to next file onError
我在目录中的文件中循环浏览,我需要在其中打开每个文件,进行一些操作然后将其关闭。
有时,Workbooks.Open会因错误而失败,我只是想显示一个MsgBox,然后继续执行目录循环中的下一个文件。 但是由于Error块不在循环中,所以我不能只调用'Loop'...那么我该怎么做?
下面的测试立即触发一个错误,如果没有“ For”,则无法调用“ Loop” ...
Sub test()
Dim folderPath As String
Dim filename As String
folderPath = 'C:\myDirectory'
filename = Dir(folderPath & "*.xlsx")
Do While filename <> ""
On Error GoTo OpenFailedError
Set wb = Workbooks.Open(folderPath & filename)
On Error GoTo 0
filename = Dir
Loop
Exit Sub
OpenFailedError:
MsgBox ("Unable to open file " & filenameString)
Loop
End Sub
这是未经测试的,但我确定会更好。
请注意,您有几个未声明的变量: wb
和filenameString
。 我强烈建议在每个模块的顶部使用Option Explicit
,以避免未声明或错误命名的变量。 在这种情况下,看起来filenameString
应该是FileName
。 另请注意,我在变量名称中添加了一些大写字母。 这有助于您在输错名称(使用小写字母)时注意到,因为它无法解析为大写。
无论如何,我都会将错误检查移到主循环中:
Sub test()
Dim FolderPath As String
Dim FileName As String
Dim wb As Excel.Workbook
FolderPath = "C:\myDirectory\"
FileName = Dir(FolderPath & "*.xlsx")
Do While FileName <> ""
On Error Resume Next
Set wb = Workbooks.Open(FolderPath & FileName)
If Err.Number <> 0 Then
MsgBox ("Unable to open file " & FileName)
End If
On Error GoTo 0
FileName = Dir
Loop
End Sub
编辑:根据Sid的建议,在FolderPath
的末尾添加了一个“ \\”。
我想知道如果尝试打开xlsx文件,为什么Set wb = Workbooks.Open()
根本失败? 除非文件已损坏?
我看到代码失败的主要原因是因为文件路径中缺少"\\"
folderPath = "C:\myDirectory"
filename = Dir(folderPath & "*.xlsx")
将以上更改为
FolderPath = "C:\myDirectory"
If Right(FolderPath, 1) <> "\" Then FolderPath = FolderPath & "\"
FileName = Dir(FolderPath & "*.xlsx")
如果您在问题中误漏了"\\"
,请遵循道格的建议(稍作修改)
我在道格的代码中添加了两行
If Right(FolderPath, 1) <> "\" Then FolderPath = FolderPath & "\"
和
Err.Clear
这是编辑后的代码。
Sub test()
Dim FolderPath As String, FileName As String
Dim wb As Excel.Workbook
FolderPath = "C:\myDirectory"
If Right(FolderPath, 1) <> "\" Then FolderPath = FolderPath & "\"
FileName = Dir(FolderPath & "*.xlsx")
Do While FileName <> ""
On Error Resume Next
Set wb = Workbooks.Open(FolderPath & FileName)
If Err.Number <> 0 Then
MsgBox ("Unable to open file " & FileName)
Err.Clear
End If
On Error GoTo 0
FileName = Dir
Loop
End Sub
我要么按照Doug Glancy的建议去做,要么定义一个辅助函数:
Function TryOpenWorkbook(ByVal FileName As String, ByRef WBook As Workbook) As Boolean
On Error Goto Except
Set WBook = Workbooks.Open(FileName)
TryOpenWorkbook = True
Exit Function
Except:
MsgBox Err.Description, vbWarning, "Error " & Err.Number
End Function
Sub Test()
Dim folderPath As String
Dim filename As String
Dim wb As Workbook
folderPath = 'C:\myDirectory'
filename = Dir(folderPath & "*.xlsx")
Do While filename <> ""
If TryOpenWorkbook(folderPath & filename, wb) Then
' do stuff...
End If
filename = Dir
Loop
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.