简体   繁体   English

Excel VBA-循环浏览目录中的文件时,如何跳至下一个文件onError

[英]Excel VBA - when looping through files in a directory, how to skip to next file onError

I'm looping through the files in a directory, where I need to open each file, do some manipulations and then close it. 我在目录中的文件中循环浏览,我需要在其中打开每个文件,进行一些操作然后将其关闭。

From time to time the Workbooks.Open fails with an error, and I simply want to display a MsgBox and then continue to the next file in the directory loop. 有时,Workbooks.Open会因错误而失败,我只是想显示一个MsgBox,然后继续执行目录循环中的下一个文件。 But since the Error block is outside the loop, I can't just call 'Loop'... so how do I do this ? 但是由于Error块不在循环中,所以我不能只调用'Loop'...那么我该怎么做?

The test below immediately triggers an error that I can't call "Loop" without a "For"... 下面的测试立即触发一个错误,如果没有“ 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

This is untested, but better, I'm sure. 这是未经测试的,但我确定会更好。

Note that you have a couple of undeclared variables: wb and filenameString . 请注意,您有几个未声明的变量: wbfilenameString I strongly recommend using Option Explicit at the top of each module to avoid undeclared or misnamed variables. 我强烈建议在每个模块的顶部使用Option Explicit ,以避免未声明或错误命名的变量。 In this case, it looks like filenameString was supposed to be FileName . 在这种情况下,看起来filenameString应该是FileName Note also that I put some capitals in the variable names. 另请注意,我在变量名称中添加了一些大写字母。 This helps you notice when you mistype a name (using lower-case letters) as it will fail to resolve to upper-case. 这有助于您在输错名称(使用小写字母)时注意到,因为它无法解析为大写。

At any rate, I'd move the error-check inside the main loop: 无论如何,我都会将错误检查移到主循环中:

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

EDIT: Per Sid's suggestion, added a "\\" to the end of FolderPath . 编辑:根据Sid的建议,在FolderPath的末尾添加了一个“ \\”。

I am wondering why would Set wb = Workbooks.Open() fail at all if you are trying to open an xlsx file? 我想知道如果尝试打开xlsx文件,为什么Set wb = Workbooks.Open()根本失败? unless the file is corrupted? 除非文件已损坏?

The main reason why I see the code failing is because it is missing a "\\" in the file path 我看到代码失败的主要原因是因为文件路径中缺少"\\"

folderPath = "C:\myDirectory"
filename = Dir(folderPath & "*.xlsx")

Change the above to 将以上更改为

FolderPath = "C:\myDirectory"

If Right(FolderPath, 1) <> "\" Then FolderPath = FolderPath & "\"

FileName = Dir(FolderPath & "*.xlsx")

And if you missed the "\\" by mistake in your question, then follow what Doug suggested (with a slight edit) 如果您在问题中误漏了"\\" ,请遵循道格的建议(稍作修改)

I added two lines to Doug's code 我在道格的代码中添加了两行

If Right(FolderPath, 1) <> "\" Then FolderPath = FolderPath & "\"

and

Err.Clear

Here is the edited code. 这是编辑后的代码。

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

the easiest way is to use on error resume next but that wont let you handle errors, it will just skip it. 最简单的方法是接下来使用错误恢复,但这不会让您处理错误,它只会跳过它。

to handle errors you can use on error go to . 处理错误时可以使用的错误去。 here are some examples of how to use both. 这是一些如何同时使用两者的示例。

On Error 错误时

I'd either do what Doug Glancy suggests or define a helper function: 我要么按照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.

相关问题 遍历目录VBA中的所有文件 - Looping through all files in directory VBA Excel/vba:如果出错,如何跳到下一张工作表? - Excel/vba: How to skip to next sheet if error? VBA 循环遍历一个目录中的文件,在另一个目录中另存为 csv,如果文件存在则跳过 - VBA Loop through files in a directory, save as csv in another directory, skip if file exists VBA遍历选定目录中的excel文件-复制数据并粘贴到不同的工作表中 - VBA Looping through excel files in selected directory - Copy data and paste in different sheets 使用 Excel VBA Dir() 函数循环并打开文件目录提前退出 - Looping through and opening a directory of files with Excel VBA Dir() function quitting early 通过文件扩展名循环,excel vba - Looping through file extensions, excel vba Excel VBA:遍历.msg文件目录 - Excel VBA: Loop Through a Directory of .msg files Excel VBA代码,用于循环浏览文件并将特定数据复制到一个文件 - Excel VBA code for Looping through files and copying specific data to one file 为什么我的Html到Excel转换在循环浏览文件时会随着时间的推移而减慢使用VBA? - Why my Html to Excel conversion slows down using VBA over time when looping through files? Excel VBA - 如何在“直到……循环”中跳到下一次迭代 - Excel VBA - how to skip to next iteration in a Do Until...Loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM