我有一个小循环来检查所有工作表,并在满足某些条件时复制列。但是,毕竟所有工作表都完成了,我遇到了"运行时错误92:对于未初始化的循环"。我了解,只要循环运行(直到最后一个工作表)或发生错误,Next ws
就会被解决。我不明白为什么循环完成后使用Next ws
。
你有什么想法我在做什么?
非常感谢!
Dim MonthBC As String
Dim YearBC As String
Dim Phase As String
Dim colBC As Long
Dim colNo As Long
Dim vCol As Variant
Dim coli As Long
MonthBC = Form_Start_Update.ComboBox_Month.Value
YearBC = Form_Start_Update.ComboBox_Year.Value
Phase = "Plan"
For Each ws In ThisWorkbook.Worksheets
With ws
Debug.Print ws.Range("A1").Parent.Name
colNo = ws.Cells(8, Columns.Count).End(xlToLeft).Column
vCol = Application.WorksheetFunction.Transpose(ws.Range(Cells(8, 1).Address, Cells(10, colNo).Address).Value2)
If colNo = 1 Then
GoTo Continue_Next
Else
For coli = LBound(vCol, 1) To UBound(vCol, 1)
On Error GoTo Continue_Next
If IsDate(vCol(coli, 1)) = True Then
vCol(coli, 1) = Year(vCol(coli, 1))
End If
If vCol(coli, 1) = YearBC Then
If vCol(coli, 2) = MonthBC Then
If vCol(coli, 3) = Phase Then
colBC = coli
ws.Range(Cells(1, colBC + 1).Address).EntireColumn.Insert
ws.Range(Cells(1, colBC).Address, Cells(Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row, colBC).Address).Copy
ws.Range(Cells(1, colBC + 1).Address).PasteSpecial Paste:=xlPasteValues
ws.Range(Cells(11, 10).Address, Cells(Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row, 10).Address).Copy
ws.Range(Cells(11, colBC).Address).PasteSpecial Paste:=xlPasteFormulas
End If
End If
End If
Next coli
End If
End With
Continue_Next:
Next ws
问题是在循环内使用标签。更改代码的逻辑并摆脱它们。仅供参考,您需要重置错误处理程序时,当您在错误上获得标签时,您还是想摆脱标签。
/e:更确切地说,on error goto Continue_Next
转到了循环外部的标签,我相信这会导致错误。如果您期望在这里错误,请将On Error Resume Next
放在顶部,测试您的错误,然后If Err.Number > 0 then Exit For
-不需要标签。请记住要清除错误和错误处理过程。尝试这样的事情:
For Each ws In ThisWorkbook.Worksheets
Debug.Print ws.Range("A1").Parent.Name
colNo = ws.Cells(8, Columns.count).End(xlToLeft).Column
vCol = Application.WorksheetFunction.Transpose(ws.Range(Cells(8, 1).Address, Cells(10, colNo).Address).Value2)
If colNo > 1 Then
For coli = LBound(vCol, 1) To UBound(vCol, 1)
On Error Resume Next
'test your error
If Err.number > 0 Then Exit For
On Error GoTo 0
If IsDate(vCol(coli, 1)) = True Then vCol(coli, 1) = Year(vCol(coli, 1))
If vCol(coli, 1) = YearBC Then
If vCol(coli, 2) = MonthBC Then
If vCol(coli, 3) = Phase Then
colBC = coli
ws.Range(Cells(1, colBC + 1).Address).EntireColumn.Insert
ws.Range(Cells(1, colBC).Address, Cells(Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).row, colBC).Address).Copy
ws.Range(Cells(1, colBC + 1).Address).PasteSpecial Paste:=xlPasteValues
ws.Range(Cells(11, 10).Address, Cells(Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).row, 10).Address).Copy
ws.Range(Cells(11, colBC).Address).PasteSpecial Paste:=xlPasteFormulas
End If
End If
End If
Next coli
On Error GoTo 0
End If
Next ws