简体   繁体   中英

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. But since the Error block is outside the loop, I can't just call 'Loop'... so how do I do this ?

The test below immediately triggers an error that I can't call "Loop" without a "For"...

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 . I strongly recommend using Option Explicit at the top of each module to avoid undeclared or misnamed variables. In this case, it looks like filenameString was supposed to be 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 .

I am wondering why would Set wb = Workbooks.Open() fail at all if you are trying to open an xlsx file? 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM