excel - VBA 中的 OR 运算符用法

标签 excel vba

我试图弄清楚如何使用 Or VBA 中的运算符。我对这种语言不是很熟悉,你也许能说出来。

代码的以下部分工作得很好:

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

最佳答案

您需要使用 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

关于excel - VBA 中的 OR 运算符用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55164420/

相关文章:

Excel VBA - 配置 MS 项目资源表

vba - Excel VBA 将多行数据连接成一行

vba - 在 VBA 中为 protected Excel 工作表指定用户权限

excel - 如何跟踪我的 Excel 工作表的用户?

VBA计算包含指定值的列中的单元格

c# - 如何遍历 Excel 工作表仅从特定列中提取数据

vba - 运行时错误 '1004' : Paste Method Of worksheet Class Failed error

excel - VBA - If 语句引用不同工作表中单元格中的特定文本

vba - 在 Excel 用户表单中嵌入来自 URL 的图像

Excel 排序顺序 - 特殊字符不排在前面