VBAsorting不会sorting,不可预知的循环

我正在运行一个macros来从工作簿中删除格式,对列s中的值进行降序删除,其值在0.501以下。 我在这里得到了一些帮助来修复部分代码

但是,我发现了其他问题。 代码看起来相当不可预测。 根据列s降序sorting不会对所有工作表中的行进行sorting。 如果我将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代码行应参考您正在使用的工作表。 所以,它应该使用.Range(...而不是Range(...) 。在你的情况下,它会抛出一个错误,因为sorting键也必须引用工作表。

最终的代码应该如下所示:

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