VBA sort decending not sorting, unpredictable looping

て烟熏妆下的殇ゞ 提交于 2019-12-24 16:18:13

问题


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.


回答1:


The .Sort line of code should refer to the Worksheet with which you are working. So, it should use .Range(... instead of just Range(...). In your case, it throws an error because the sort key must also refer to the worksheet.

Final code should look something like:

.Range("A2:v" & endrow).Sort _
Key1:=.Range("s2"), Order1:=xlDescending


来源:https://stackoverflow.com/questions/29143398/vba-sort-decending-not-sorting-unpredictable-looping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!