只是一个简单的问题。假设我有四列数据A,B,C和D.
A B C D
10 1 10 8
40 2 30 9
30 3 60 12
60 4 50 11
50 5 40 13
20 6 20 15
如何根据A的顺序对C列和D列进行排序?即我想要以下结果;
A B C D
10 1 10 8
40 2 40 13
30 3 30 9
60 4 60 12
50 5 50 11
20 6 20 15
查看C列如何排列为与A相同,D中与C中相邻单元格对应的值随之移动。我尝试突出显示所有列并根据列A对数据进行排序,但它不起作用。有什么想法吗?
此致 耶
答案 0 :(得分:0)
在您的VBA IDE中,转到工具菜单并选择参考。选择" Microstoft ActiveX数据对象2.8库。
Private Sub CommandButton26_Click()
Dim rs As New ADODB.Recordset
Dim ws As Excel.Worksheet
Dim lrow As Long
Set ws = Application.ActiveSheet
'Add fields to your recordset for storing data.
With rs
.Fields.Append "Row", adInteger
.Fields.Append "ColumnC", adInteger
.Fields.Append "ColumnD", adInteger
.Open
End With
lrow = 1
'Loop through and record what is in Columns C and D
Do While lrow <= ws.UsedRange.Rows.count
rs.AddNew
rs.Fields("Row").Value = lrow
rs.Fields("ColumnC").Value = ws.Range("C" & lrow).Value
rs.Fields("ColumnD").Value = ws.Range("D" & lrow).Value
rs.Update
lrow = lrow + 1
ws.Range("A" & lrow).Activate
Loop
'Now go through and rewrite columns C and D based on what is in A
lrow = 1
Do While lrow <= ws.UsedRange.Rows.count
rs.Filter = ""
rs.Filter = "ColumnC='" & ws.Range("A" & lrow).Value & "'"
'If we have a match, write C and D
If rs.RecordCount > 0 Then
ws.Range("C" & lrow).Value = rs.Fields("ColumnC").Value
ws.Range("D" & lrow).Value = rs.Fields("ColumnD").Value
End If
lrow = lrow + 1
Loop
End Sub
答案 1 :(得分:0)
以下是您使用的一个小宏,它将根据A列对列C进行排序,列D将自动排序。
它使用 'MATCH'
功能。我已根据您的理解发表评论
假设您的数据位于A:D列并且具有标题。
Sub test1()
Dim sht As Worksheet
Dim rw As Long
'SELECTING THE SHEET (CHANGE ME)
Set sht = Sheets("Sheet2")
'SETTING # OF ROWS
rw = sht.UsedRange.Rows.Count
'LOOPING AND PLACING FORMULA IN TEMPORARY COLUMN E
For i = 2 To rw
sht.Cells(i, 5).Value = "=MATCH(C" & i & ",$A$2:$A$" & rw & ",0)"
Next
'SORTING COLUMNS C,D AND E IN ASCENDING ORDER (WHICH WILL BE EXACTLY LIKE COLUMN A)
Range("C2:E" & rw).Sort Key1:=Range("E2:E" & rw), Order1:=xlAscending
'CLEARING THE TEMPORARY COLUMN E
Range("E2:E" & rw).Clear
'RELEASING THE OBJECT
Set sht = Nothing
End Sub