|
Sub OrganizeData()
Dim ws As Worksheet
Dim lastRow As Long, lastCol As Long
Dim i As Long
Dim currentSequence As Long
Dim currentValue As String
Dim previousValue As String
' 使用工作表编号
Set ws = ThisWorkbook.Sheets(1)
' 找到最后一行
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
' 找到最后一列
lastCol = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column
' 对整表按A列和B列进行排序
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add Key:=ws.Range(ws.Cells(3, 1), ws.Cells(lastRow, 1)), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ws.Sort.SortFields.Add Key:=ws.Range(ws.Cells(3, 2), ws.Cells(lastRow, 2)), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ws.Sort
.SetRange ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol)) ' 包括所有行
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
' 在B列右侧增加两列空列
ws.Range(ws.Cells(1, 3), ws.Cells(lastRow, 4)).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
' 初始化变量
currentSequence = 0
previousValue = ""
' 遍历第三行到最后一行的数据
For i = 3 To lastRow
currentValue = ws.Cells(i, 2).Value ' B列的值
' 若当前值与前一个值不同,重新开始排序
If currentValue <> previousValue Then
currentSequence = 1
Else
currentSequence = currentSequence + 1
End If
' 在D列填充顺序号
ws.Cells(i, 4).Value = currentSequence
' 在C列填充B列的值、"-"和顺序号
ws.Cells(i, 3).Value = currentValue & "-" & currentSequence
' 更新前一个值
previousValue = currentValue
Next i
End Sub
|
|