【发布时间】:2020-12-18 15:56:34
【问题描述】:
我正在尝试对 Excel 工作表中的一系列行进行排序,这些行都以第一列中的特定绿色背景颜色开头,但我的 vba 代码根本不这样做,我不明白为什么。目标是作为一个例子从中得到:
Private Sub Sort_Click()
Dim StartRow, EndRow, i As Integer
Dim row As Range, cell As Range
'Discover the data starting and end rows
i = 1
StartRow = 1
EndRow = 1
'Check the first cell of each row for the start of background colour
For Each row In ActiveSheet.UsedRange.Rows
Set cell = Cells(row.row, 1)
If i < 3 Then
If Hex(cell.Interior.Color) = "47AD70" And i = 1 Then
StartRow = row.row
i = 2
ElseIf Hex(cell.Interior.Color) <> "47AD70" And i = 2 Then
EndRow = row.row - 1
i = 3
End If
End If
Next row
'Sort the range
Range("A" & StartRow & ":" & "A" & EndRow).Sort Key1:=Range("A" & StartRow & ":" & "A" & EndRow), Order1:=xlAscending, Header:=xlNo
End Sub
代码应检查“A”列中每一行的第一个单元格,直到它到达第一个绿色背景颜色,在该颜色处将该行号分配给变量 StartRow。循环继续,直到它不再检测到第一个单元格中的绿色背景颜色。然后它将该行号 - 1 分配给变量 EndRow。最后,它使用 StartRow 和 EndRow 作为范围对绿色范围进行数字排序。 Range 语句部分可能无法正常工作。我想知道是否有人可以一起提供解决方案或更好的代码。这些图像展示了手动排序的绿色范围内的行。提前致谢
【问题讨论】: