我正在運行一個宏以從工作簿中刪除格式,排序列降序刪除列中s值低於0.501的行。 I received some help to fix part of the code hereVBA排序降序不排序,不可預知的循環
但是,我發現了其他問題。代碼看起來很不可預測。根據列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
結束子
任何見解調查這些問題,將不勝感激。
乍一看,這似乎是錯誤的:'範圍( 「A2:V2」 &endrow)'。它不應該是'Range(「A2:V」&endrow)''。否則,它將採取任何最後一行,並在它之前添加一個2。 (例如,如果endrow是50,而不是來自'A2:V50'的Range,它將變成'A2:V250' – user3561813 2015-03-19 12:47:24
另一個評論。你是否打算在刪除所有必要的行後對每個工作表進行排序? ,代碼在每次迭代之後通過內部循環(刪除相應單元格的循環)對工作表進行排序。 – user3561813 2015-03-19 12:51:11
@ user3561813好點!我可以將它從內部循環中移出。 – 2015-03-19 12:54:11