我试图弄清楚如何在VBA中使用Or
运算符。我对这种语言不是很熟悉,您可能会说出来。
代码的以下部分工作正常:
FirstRow = 2
LastRow = Cells(Rows.Count, "K").End(xlUp).Row - 1
For r = LastRow To FirstRow Step -1
If Cells(r, "K") <> 114 Then
Rows(r).Delete
End If
Next r
它删除不包含数字114的行。问题是我也想包括数字136和139。我只想在K列中保留包含114、136或139的行(加上标题和汇总行)。
我尝试了一些类似于:
FirstRow = 2
LastRow = Cells(Rows.Count, "K").End(xlUp).Row - 1
For r = LastRow To FirstRow Step -1
If Cells(r, "K") <> 114 Or _
Cells(r, "K") <> 136 Or _
Cells(r, "K") <> 139 Then
Rows(r).Delete
End If
Next r
这些代码仅删除标题和摘要行以外的所有内容。
我在做什么错了?
完整代码:
Sub SouthEast()
Dim answer As Integer
answer = MsgBox("Continue?", vbYesNo + vbQuestion, "Show only South East")
If answer = vbYes Then
Dim r As Long
Dim FirstRow As Long
Dim LastRow As Long
FirstRow = 2
LastRow = Cells(Rows.Count, "K").End(xlUp).Row - 1
For r = LastRow To FirstRow Step -1
If Cells(r, "K") <> 114 Or _
Cells(r, "K") <> 136 Or _
Cells(r, "K") <> 139 Then
Rows(r).Delete
End If
Next r
Else
'Do nothing
End If
End Sub
答案 0 :(得分:3)
在这种情况下,您需要像这样使用And
运算符:
If Cells(r, "K") <> 114 And _
Cells(r, "K") <> 136 And _
Cells(r, "K") <> 139 Then
Rows(r).Delete
End If
如果要检查是否相等,则可以使用Or
。
赞:
If Cells(r, "K") = 114 Or _
Cells(r, "K") = 136 Or _
Cells(r, "K") = 139 Then
Rows(r).Delete
End If
答案 1 :(得分:2)
这是一个典型的逻辑错误:您在谈论:
Not(
(value == 114) OR
(value == 136) OR
(value == 139))
这等于:
Not(value == 114) AND
Not(value == 136) AND
Not(value == 139)
等于:
(value <> 114) AND
(value <> 136) AND
(value <> 139)
答案 2 :(得分:2)
使用And
Or
调用TRUE
And
如果所有全部值为true,则调用TRUE
Sub SouthEast()
Dim answer As Integer
answer = MsgBox("Continue?", vbYesNo + vbQuestion, "Show only South East")
If answer = vbYes Then
Dim r As Long
Dim FirstRow As Long
Dim LastRow As Long
FirstRow = 2
LastRow = Cells(Rows.Count, "K").End(xlUp).Row - 1
For r = LastRow To FirstRow Step -1
If Cells(r, "K") <> 114 And _
Cells(r, "K") <> 136 And _
Cells(r, "K") <> 139 Then
Rows(r).Delete
End If
Next r
Else
'Do nothing
End If
End Sub
答案 3 :(得分:0)
我的答案与上述类似,但我想强调一些细节。
我认为最好使用 .value
Option Explicit
Sub SouthEast()
Dim answer As Integer
Dim r As Long, FirstRow As Long, LastRow As Long
answer = MsgBox("Continue?", vbYesNo + vbQuestion, "Show only South East")
If answer = vbYes Then
With ThisWorkbook.Worksheets("Sheet1")
FirstRow = 2
LastRow = .Cells(.Rows.Count, "K").End(xlUp).Row - 1
For r = LastRow To FirstRow Step -1
If .Cells(r, "K").Value <> 114 And _
.Cells(r, "K").Value <> 136 And _
.Cells(r, "K").Value <> 139 Then
.Rows(r).Delete
End If
Next r
End With
Else
'Do nothing
End If
End Sub