I am running a macro to remove formatting from a workbook, sort column s descending delete rows where values in column s are under 0.501. I received some help to fix part of the code here
However, I have found additional problems. The code appears quite unpredictable. Sort descending based on column s does not sort the rows in all of the sheets. if I change Range
to .Range
the code breaks.
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
Any insights into these problems would be much appreciated.