sub不会循环通过第二个if语句vba

真的希望有人能帮助我。 所以我有下面的代码。 独立的代码自己可以正常工作,但是在执行脚本时,它只能通过第一个条件循环。 我想要做的是循环遍历所有的代码,每次。 我认为这是一个小的东西我想念,但我似乎无法find一个解决scheme。

Sub Copypre() Dim i As Integer Dim n As Integer For i = 2 To 10 'Checks the number of entries in the "Pre" table, to make sure that there are no spaces between the lines On Error Resume Next n = Worksheets("Pre").Range("A2:A6000").Cells.SpecialCells(xlCellTypeConstants).Count If n = Null Then n = i 'Goes through the different sheets to find all "pre" values and paste them in the "Pre" sheet If ThisWorkbook.Sheets("273").Range("A" & i).Value = "Pre" Then Range(Cells(i, 1), Cells(i, 3)).Select Selection.Copy Sheets("Pre").Select Range("A" & n).Select ActiveSheet.Paste Sheets("2736").Select End If End If Next i End Sub 

你的代码有几个问题,但主要的问题可能是, If n = Null永远不会是真的,因为一个整数不能为Null 。 你可以改变这个If n = 0

几件事情要考虑:

error handling:尽可能快地返回On Error GoTo 0正常error handling。 这样你就会知道(假设你的工作簿中没有工作表"2736" ),你的代码试图select一个不存在的工作表。

范围参数:当使用Range (和Cells )参数时,不指定表单时要小心。 当您在select的不同工作表之间切换回来和第四次时,会发生变化,您可能会疏忽跟踪Range正在返回的数据表。 考虑申报每个工作表,然后复制你的范围,如:

 Dim w273 As Worksheet Set w273 = ThisWorkbook.Sheets("273") w273.Range(w273.Cells(i, 1), w273.Cells(i, 3)).Copy 

循环可以快速消耗时间长的数据列,我怀疑你的代码是严重的编辑。 尝试将这种替代方法复制到目标工作表中。

 Sub Copypre() With Sheets("273").Cells(1, 1).CurrentRegion .AutoFilter .Columns(1).AutoFilter field:=1, Criteria1:="=Pre" If CBool(Application.Subtotal(103, .Offset(1, 0))) Then .Offset(1, 0).Resize(, 3).Copy _ Destination:=Sheets("Pre").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) End If .AutoFilter End With End Sub 

所有这些都可以在没有一个variables的情况下完成。

附录:

至于你原来的问题,整个if "pre"/copy/paste部分嵌套在if n = Null所以只有当n = Null为真才能达到。 如果没有.SpecialCells(xlCellTypeConstants)进行计数,则n将被赋予其默认值(例如0 )。 不等于零,所以条件永远不会满足。 要检查您的代码,请添加以下行。

 On Error Resume Next n = Worksheets("Pre").Range("A2:A6000").Cells.SpecialCells(xlCellTypeConstants).Count Debug.Print "n is " & n 

运行后,用Ctrl+G打开即时窗口。 如果在Pre!A2:A6000中没有非公式值,您应该看到n is 0

感谢所有的build议。 无效的技巧奏效! 我对VBA是全新的,所以从专家那里得到一些技巧和窍门是很好的。 我会尽量使代码更简单,因为这不是很优雅。 关于床单,我完全可以理解这个困惑,我也修正了这个问题。 它现在工作,看起来像这样:

 Sub Copypre() Dim i As Integer Dim n As Integer For i = 2 To 5000 ' Checks the number of entries in the "Pre" table, to make sure that there are no spaces between the lines On Error Resume Next n = Worksheets("Pre").Range("A2:A6000").Cells.SpecialCells(xlCellTypeConstants).Count ' Goes through the different sheets to find all pre values and paste them in the "Pre" sheet If ThisWorkbook.Sheets("2736").Range("A" & i).Value = "Pre" Then Sheets("2736").Select Sheets("2736").Range(Cells(i, 1), Cells(i, 3)).Select Selection.Copy Sheets("Pre").Select Range("A" & (n + 2)).Select ActiveSheet.Paste Sheets("2736").Select Sheets("2736").Select Range(Cells(i, 5), Cells(i, 6)).Select Selection.Copy Sheets("Pre").Select Range("E" & (n + 2)).Select ActiveSheet.Paste Sheets("2736").Select End If Next i End Sub