在现有If Block中添加新的If语句

我有这个比较列A和B的代码,并且如果A更大,则将B加1:

Sub test07() With Sheets("Sheet1") Dim LastRow As Long, i As Long LastRow = Cells(Rows.Count, "A").End(xlUp).Row For i = 12 To LastRow If Range("A" & i).Value > Range("B" & i).Value Then Range("B" & i).Value = Range("B" & i).Value + 1 End If Next i End With End Sub 

我想再次添加相同的东西,但列C和D,但我得到语法错误,即:

 Sub test07() With Sheets("Sheet1") Dim LastRow As Long, i As Long LastRow = Cells(Rows.Count, "A").End(xlUp).Row For i = 12 To LastRow If Range("A" & i).Value > Range("B" & i).Value Then Range("B" & i).Value = Range("B" & i).Value + 1 If Range("C" & i).Value > Range("D" & i).Value Then Range("D" & i).Value = Range("D" & i).Value + 1 End If Next i End With End Sub 

任何人都可以看到我要去哪里错了吗? 非常感谢

您还应该熟悉ElseIf – ElseIf与End If相同,后跟一个新的If语句, 只不过它只在第一个If语句导致False的情况下运行。 即:假定A1 = 5,并且您想要检查A1的值来确定B1的值。 你可以用两种方法检查值:

选项1,使用End If后跟一个新的If语句:

 If Range("A1") > 3 Then B1 = 2 End If If Range("A1") > 4 Then B1 = 1 End If 'Because A1 = 5, both If statements are True, and therefore B1 will equal 1, because that is the last line of code which affects it 

选项2,使用ElseIf:

 If Range("A1") > 3 Then B1 = 2 ElseIf Range("A1") > 4 Then B1 = 1 End If 'Because A1 = 5, the first If statement is True, the ElseIf statement never runs, and therefore B1 will equal 2, because that is the only line of code which affects it. 

两种方法都是有效的 – 你只需要理解你实际使用之后的逻辑path。

正如在评论中所提到的,你错过了一个End If 。 但是,您还没有充分利用使用With … End With语句来标识工作表的显示父项。

 Sub test07() Dim lastRow As Long, i As Long With Sheets("Sheet1") lastRow = .Cells(Rows.Count, "A").End(xlUp).Row For i = 12 To lastRow If .Range("A" & i).Value > .Range("B" & i).Value Then .Range("B" & i).Value = .Range("B" & i).Value + 1 End If '<~~might have to be three lines down depending upon how you want your logic to flow If .Range("C" & i).Value > .Range("D" & i).Value Then .Range("D" & i).Value = .Range("D" & i).Value + 1 End If Next i End With End Sub 

请注意使用.Range.Cells ; 不是RangeCells 。 前缀句号(又名句号 )将范围和单元格与With ... End With引用的工作表关联起来。

回到If ... End If问题,如果你想避免closuresIf语句,你可以像下面这样使用它们。

 Sub test07() Dim lastRow As Long, i As Long With Sheets("Sheet1") lastRow = .Cells(Rows.Count, "A").End(xlUp).Row For i = 12 To lastRow If .Range("A" & i).Value > .Range("B" & i).Value Then _ .Range("B" & i).Value = .Range("B" & i).Value + 1 If .Range("C" & i).Value > .Range("D" & i).Value Then _ .Range("D" & i).Value = .Range("D" & i).Value + 1 Next i End With End Sub 

此方法仅适用于在If代码行之后的单个相关代码行。

你可以简单地复制/粘贴你的代码并修改

 Range("A" & i) --> Range("A" & i).Offset(#rows,#cols) 

或者甚至更好,沟渠“范围”,并使用“细胞”与两个迭代器和一个嵌套的FOR循环…

 With... for i in {#rowStart} To {#rowEnd} for j in {#colstart} To {#Colend} .Cells(i,j).Value = {put stuff here} 

使用Ubound(Range())来对一个数组中的元素进行计数,并设置你的i&j等等。