gpt4 book ai didi

vba - 在现有 If block 中添加新的 If 语句

转载 作者:行者123 更新时间:2023-12-02 15:16:26 24 4
gpt4 key购买 nike

我有这段代码,可以比较 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

有人能看出我哪里出了问题吗?非常感谢

最佳答案

正如评论中提到的,您缺少 End If。但是,您也没有充分利用使用 With ... End With statement 带来的显式出身。识别工作表。

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 的使用;不是范围单元格。前缀句点(又名句号)将范围和单元格与With ... End With中引用的工作表相关联。

回到 If ... End If 问题,如果您希望避免关闭 If 语句,您可以使用他们喜欢以下内容。

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 代码行之后的单个相关代码行。

关于vba - 在现有 If block 中添加新的 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35258249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com