VBA降序排序不排序,不可预知的循环
VBA sort decending not sorting, unpredictable looping
我是运行一个宏,用于从工作簿中删除格式,对 s 列进行降序排序删除列 s 中的值低于 0.501 的行。
但是,我发现了其他问题。代码看起来相当不可预测。 Sort descending based on column s 不会对所有工作表中的行进行排序。如果我将 Range
更改为 .Range
,代码就会中断。
Sub sort_delete_500cust()
Dim WS_Count As Integer
Dim i, K As Integer
Dim endrow As Long
Dim output_wb As Workbook
' Set WS_Count equal to the number of worksheets in the active
' workbook.
Set output_wb = Workbooks("DMA_customers_5.xlsx")
With output_wb
WS_Count = output_wb.Worksheets.count
' Begin the loop.
For i = 1 To WS_Count
With output_wb.Worksheets(i)
'.Cells.ClearFormats
'MsgBox ActiveWorkbook.Worksheets(I).Name
endrow = .Range("a" & .Rows.count).End(xlUp).Row
'Worksheets(i).Cells.UnMerge
'key is the sort by column' only works if cells are unmerged
Range("A2:v" & endrow).Sort _
Key1:=Range("s2"), Order1:=xlDescending
For K = endrow To 2 Step -1
If CDec(.Cells(K, 19).Value) < 0.501 Then
'You need to traverse your K loop in reverse order. Otherwise rows will be skipped as you delete because they are shifted up by the delete operation and you K value increments over them.
.Range("S" & K).EntireRow.Delete
End If
Next K
End With
Next i
End With
结束子
任何对这些问题的见解都将不胜感激。
.Sort
行代码应引用您正在使用的 Worksheet
。所以,它应该使用 .Range(...
而不是 Range(...)
。在您的情况下,它会引发错误,因为排序键还必须引用工作表。
最终代码应如下所示:
.Range("A2:v" & endrow).Sort _
Key1:=.Range("s2"), Order1:=xlDescending
我是运行一个宏,用于从工作簿中删除格式,对 s 列进行降序排序删除列 s 中的值低于 0.501 的行。
但是,我发现了其他问题。代码看起来相当不可预测。 Sort descending based on column s 不会对所有工作表中的行进行排序。如果我将 Range
更改为 .Range
,代码就会中断。
Sub sort_delete_500cust()
Dim WS_Count As Integer
Dim i, K As Integer
Dim endrow As Long
Dim output_wb As Workbook
' Set WS_Count equal to the number of worksheets in the active
' workbook.
Set output_wb = Workbooks("DMA_customers_5.xlsx")
With output_wb
WS_Count = output_wb.Worksheets.count
' Begin the loop.
For i = 1 To WS_Count
With output_wb.Worksheets(i)
'.Cells.ClearFormats
'MsgBox ActiveWorkbook.Worksheets(I).Name
endrow = .Range("a" & .Rows.count).End(xlUp).Row
'Worksheets(i).Cells.UnMerge
'key is the sort by column' only works if cells are unmerged
Range("A2:v" & endrow).Sort _
Key1:=Range("s2"), Order1:=xlDescending
For K = endrow To 2 Step -1
If CDec(.Cells(K, 19).Value) < 0.501 Then
'You need to traverse your K loop in reverse order. Otherwise rows will be skipped as you delete because they are shifted up by the delete operation and you K value increments over them.
.Range("S" & K).EntireRow.Delete
End If
Next K
End With
Next i
End With
结束子
任何对这些问题的见解都将不胜感激。
.Sort
行代码应引用您正在使用的 Worksheet
。所以,它应该使用 .Range(...
而不是 Range(...)
。在您的情况下,它会引发错误,因为排序键还必须引用工作表。
最终代码应如下所示:
.Range("A2:v" & endrow).Sort _
Key1:=.Range("s2"), Order1:=xlDescending