VBA 如果值小于指定值则删除整行 - 删除错误的行
VBA Delete entire row if value is less than specified value - deletes wrong rows
我正在尝试 运行 一个搜索工作表 S 列的小宏,如果 S 列中的值 <0.501,它会删除该行。
我现在 运行ning 的代码删除了一些行,但似乎是随机删除的,而不是基于 s 中的单元格值。任何人都可以看到我的错误是从哪里来的吗?
Sub sort_delete_500cust()
Dim WS_Count As Integer
Dim I, K As Integer
Dim endrow As Long
' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = Workbooks("Standard.xlsx").Worksheets.count
' Begin the loop.
For I = 1 To WS_Count
With Worksheets(I)
endrow = .Range("a" & .Rows.count).End(xlUp).row ' only works if cells are unmerged
Range("A2:v2" & endrow).Sort _
Key1:=Range("s2"), Order1:=xlDescending 'key is the sort by column
For K = 2 To endrow
If .Cells(K, 19).Value < 0.501 Then
.Range("S" & K).EntireRow.Delete
End If
Next K
End With
Next I
End Sub
干杯!
您需要以相反的顺序遍历 K
循环。否则,当您删除时,行将被跳过,因为它们被删除操作向上移动并且您的 K
值在它们之上递增。
For K = endrow To 2 Step -1
If CDec(.Cells(K, 19).Value) < CDec(0.501) Then
.Range("S" & K).EntireRow.Delete
End If
Next
我正在尝试 运行 一个搜索工作表 S 列的小宏,如果 S 列中的值 <0.501,它会删除该行。
我现在 运行ning 的代码删除了一些行,但似乎是随机删除的,而不是基于 s 中的单元格值。任何人都可以看到我的错误是从哪里来的吗?
Sub sort_delete_500cust()
Dim WS_Count As Integer
Dim I, K As Integer
Dim endrow As Long
' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = Workbooks("Standard.xlsx").Worksheets.count
' Begin the loop.
For I = 1 To WS_Count
With Worksheets(I)
endrow = .Range("a" & .Rows.count).End(xlUp).row ' only works if cells are unmerged
Range("A2:v2" & endrow).Sort _
Key1:=Range("s2"), Order1:=xlDescending 'key is the sort by column
For K = 2 To endrow
If .Cells(K, 19).Value < 0.501 Then
.Range("S" & K).EntireRow.Delete
End If
Next K
End With
Next I
End Sub
干杯!
您需要以相反的顺序遍历 K
循环。否则,当您删除时,行将被跳过,因为它们被删除操作向上移动并且您的 K
值在它们之上递增。
For K = endrow To 2 Step -1
If CDec(.Cells(K, 19).Value) < CDec(0.501) Then
.Range("S" & K).EntireRow.Delete
End If
Next