我必须对Excel Sheet的特定范围进行排序,其中包含不同的合并单元格,如何对其进行排序。排序列包含唯一条目。有人可以告诉我如何对它进行排序,因为excel的内置排序算法不会对不相同的单元格进行排序。
答案 0 :(得分:0)
这是我对包含非相同合并单元格的excel范围进行排序的答案。 我们必须排序的范围的名称是" SortRangeValue"我们正在对名为" column1"的列执行排序这是" SortRangeValue"的第四列。范围。完成排序在这种情况下要排序的列" column1"这是该范围内的第一列。 这是代码,执行时需要一些时间,因为没有行增加,并且在我给定的范围内,我最后有一个隐藏的行,这就是为什么我运行我的代码直到lastRow-3,这里3代表1表示隐藏行,1表示长度-1表示冒泡排序,1表示0表示索引(表示1 + 1 + 1 = 3)
Private Sub Ascending_Click()
Dim myRange As Range 'variable to hold the Named Range
Dim rowCount As Long 'variable to hold the Number of Rows in myRange
Dim colCount As Long 'variable to hold the Number of Columns in myRange
Dim rowStartIndex As Long 'variable to hold the Starting Row index of myRange
Dim colStartIndex As Long 'variable to hold the Starting Col index of myRange
Dim iIndex As Long 'Variable used for iteration
Dim jIndex As Long 'Variable used for iteration
Dim current As Long 'used in bubble sort to hold the value of the current jIndex item
Dim currentPlusOne As Long 'used in bubble sort to hold the value of the jIndex+1 item
Dim rowIndex As Long
Application.ScreenUpdating = False 'dont update screen until we sort the range.
Set myRange = Range("SortRangeValue") 'Get the range
'
'get the columns and rows from where the row start, since Range can start from any cell
' also the no. of columns and rows in rows
rowStartIndex = myRange.Row
colStartIndex = myRange.Column
colCount = myRange.Columns.Count
rowCount = myRange.Rows.Count
Dim tempCal As Long
tempCal = rowCount + rowStartIndex ' get the row no of last range
'here colStartIndex is the very first column which is to be sorted
For iIndex = 0 To rowCount - 3 Step 1 ' Run a bubble sort loop
For jIndex = 0 To rowCount - iIndex - 3 Step 1
rowIndex = jIndex + rowStartIndex
current = Cells(rowIndex, colStartIndex) ' calculate the rowIndex
currentPlusOne = Cells(rowIndex + 1, colStartIndex) ' get current cell value, and next row cell value.
If current > currentPlusOne Then 'campair the values
' if match found, select entire row of the values and shift it them down by copying it to some temp location here it is (3,16)
'get entire row from firstCol(colStartIndex) to last column (colStartIndex+colCount-1)
Range(Cells(rowIndex + 1, colStartIndex), Cells(rowIndex + 1, colStartIndex + colCount - 1)).Copy Destination:=Cells(3, 16)
Range(Cells(rowIndex, colStartIndex), Cells(rowIndex, colStartIndex + colCount - 1)).Copy Destination:=Cells(rowIndex + 1, colStartIndex)
Range(Cells(3, 16), Cells(3, 16 + colCount - 1)).Copy Destination:=Cells(rowIndex, colStartIndex)
Range(Cells(3, 16), Cells(3, 16 + colCount - 1)).Value = ""
End If
Next jIndex ' increment jINdex
Next iIndex 'Increment iIndex
Application.ScreenUpdating = True 'display result on screen
End Sub