我有以下代码
Dim CO_priority As String
Dim Col_ticketage As String
CO_priority = Range("Q4").Value
Col_ticketage = Range("Q5").Value
Sheets("Inc").Select
LR = Range("CO_priority" & Rows.Count).End(xlUp).Row
For i = LR To 2 Step -1
If (Range("CO_priority" & i).Value = "1" And Range("Col_ticketage" & i).Value < "1") Then Rows(i).delete
Next I
我希望此代码删除行,如果在变量&#34; CO_priority&#34;中给出的列中值为1并且在另一个变量&#34; Col_ticketage&#34;值小于1.
因此,假设列A中的单元格中的数字为1,而列B的数字小于1,则应删除此行,但在任何其他情况下,该行应保留。
以上代码因某种原因删除了每一行。
你能告诉我这段代码有什么问题吗?
答案 0 :(得分:1)
更快捷的方法是使用DelRng
合并所有通过2条件的行,然后立即删除整个范围。
<强>代码强>
Option Explicit
Sub DelRows()
Dim CO_priority As String
Dim Col_ticketage As String
Dim LR As Long, i As Long
Dim DelRng As Range
CO_priority = Range("Q4").Value
Col_ticketage = Range("Q5").Value
With Sheets("Inc")
LR = .Range(CO_priority & .Rows.Count).End(xlUp).Row
For i = LR To 2 Step -1
If (.Range(CO_priority & i).Value = 1 And .Range(Col_ticketage & i).Value < 1) Then
If Not DelRng Is Nothing Then
Set DelRng = Application.Union(DelRng, .Rows(i))
Else
Set DelRng = .Rows(i)
End If
End If
Next i
End With
' make sure DelRng is not nothing >> delete entire rows at one-shot
If Not DelRng Is Nothing Then DelRng.Delete
End Sub