我正在运行一个宏来从工作簿中删除格式,对列s的降序行进行排序,其中列s中的值小于0.501。 I received some help to fix part of the code here
但是,我发现了其他问题。代码似乎非常不可预测。基于列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
End Sub
非常感谢对这些问题的任何见解。
答案 0 :(得分:1)
.Sort
代码行应引用您正在使用的Worksheet
。因此,它应该使用.Range(...
而不仅仅是Range(...)
。在您的情况下,它会抛出一个错误,因为排序键也必须引用工作表。
最终代码应该类似于:
.Range("A2:v" & endrow).Sort _
Key1:=.Range("s2"), Order1:=xlDescending