VBA错误检查循环

时间:2017-11-07 11:06:40

标签: excel vba excel-vba

我有以下代码,用于循环遍历~200个工作簿,应用过滤器,并将过滤后的数据复制回主工作簿。我如何跳过任何引发错误并继续下一个值的文件名?

文件名在单元格(i,7)中,i是我的计数变量

For i = 7 To 46
'Define Sheet Name and open

DataBook.Sheets("Filename").Select
DealName = Cells(i, 7)
Set DealFileBook = Workbooks.Open(DealName)

非常感谢!谢谢

Edit1添加完整代码。

即使删除错误捕获也会导致我的excel崩溃,是否有人有更好的方法以更少的资源执行此操作?

Application.DisplayAlerts = False
Application.AskToUpdateLinks = False


Dim DealName As String
Dim DealFileBook As New Workbook
Dim DataBook As New Workbook
Dim RollBack As String

Dim i As Long


Set DataBook = ThisWorkbook


'Loop though value


'define file name
'DataBook.Sheets("Filename").Select

For i = 7 To 46


'Define Settles Sheet Name and open
On Error Resume Next
Set DealFileBook = Workbooks.Open(DealName)
On Error GoTo 0
If DealFileBook Is Nothing Then
   ' MsgBox "Error finding file name " & DealName, vbCritical
End If


'Filter for DDB and Copy
  Worksheets("Sheet1").Select
    Range("A2").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.AutoFilter
    ActiveSheet.Range("$A$2:$K$50000").AutoFilter Field:=5, Criteria1:="DDB"
    Range("A2").Select
    Range(Selection, Selection.End(xlDown)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.Copy

'paste into data book

DataBook.Activate
Worksheets("Data").Select
Range("A1").End(xlDown).Offset(1, 0).Select

Selection.PasteSpecial Paste:=xlPasteValues, _
    Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Next i

编辑3 - 完成后将发布我的代码。问题是我没有用文件名重新选择工作表

1 个答案:

答案 0 :(得分:0)

当文件名返回错误时,请尝试以下代码来处理此类错误:

On Error Resume Next
Set DealFileBook = Workbooks.Open(DealName)
On Error GoTo 0
If DealFileBook Is Nothing Then
    MsgBox "Error finding file name " & DealName, vbCritical      
End If