VBA - 较短的If / Or声明

时间:2017-08-02 16:16:32

标签: excel vba excel-vba

我一直在寻找一种更短的方式来使用这个If / Or语句,但无济于事。

Sheets("Raw").Select
Dim rowCount As Integer, rows As Integer
rows = 0
Dim CRC As String

rowCount = Range("I2", Range("I2").End(xlDown)).rows.Count
For rows = 1 To rowCount
    Range("I1").Offset(rows, 0).Select
    CRC = ActiveCell.Value
    If CRC = "Admin Cancellation" _
    Or CRC = "Building sold / Management Co changed" _
    Or CRC = "Contract Renewal delayed" _
    Or CRC = "System decommissioned" _
    Or CRC = "Building demolished" _
    Or CRC = "cancelled due to credit hold/risk" Then
        ActiveCell.rows.EntireRow.Select
        Selection.Delete Shift:=xlUp
        rows = rows - 1
        rowCount = rowCount - 1
    End If
Next rows

提前致谢!

2 个答案:

答案 0 :(得分:3)

尝试选择...案例陈述。

Dim rws As Long, rcnt As Long, crc As String

With Worksheets("Raw")
    rcnt = .Cells(.Rows.Count, "I").End(xlUp).Row
    For rws = rcnt To 2 Step -1
        Select Case LCase(.Cells(rws, "I").Value2)
            Case "admin cancellation", "building sold / management co changed", _
                 "contract renewal delayed", "system decommissioned", _
                 "building demolished", "cancelled due to credit hold/risk"
                 .Rows(rws).EntireRow.Delete
        End Select
    Next rws
End With

删除行时应始终从下到上循环,否则在删除并迭代到下一行时可能会跳过一个。这是不好的做法'将保留字重用为变量名。它也被认为是不良做法'在For .... Next循环中更改迭代var的值。

答案 1 :(得分:2)

  Select Case CRC
    Case "Admin Cancellation", "Building sold / Management Co changed", _
         "Contract Renewal delayed", "System decommissioned", "Building demolished", _
         "cancelled due to credit hold/risk"
      ' do something
  End Select