[英]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.