我正在遍历目录中的文件,我需要打开每个文件,进行一些操作然后关闭它。
Workbooks.Open有时会因错误而失败,我只想显示一个MsgBox然后继续到目录循环中的下一个文件。但由于Error块在循环之外,我不能只调用'Loop'...所以我该怎么做?
下面的测试会立即触发一个错误,我不能在没有“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
答案 0 :(得分:4)
这是未经测试的,但更好,我确定。
请注意,您有几个未声明的变量: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
的末尾添加了“\”。
答案 1 :(得分:2)
我想知道如果你试图打开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")
如果您在问题中错误地错过了"\"
,那么请按照Doug的建议(稍加编辑)
我在Doug的代码中添加了两行
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
答案 2 :(得分:0)
答案 3 :(得分:0)
我要么做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