如何使用excel按字排序每一行?

时间:2017-02-22 09:33:23

标签: excel sorting row

我有一个看起来像这样的excel文件

     A         B         C
1| A_xxxx | B_xxxx  | C_xxxx
2| B_xxxx | A_xxxx  | C_xxxx
3| C_xxxx | B_xxxx  | A_xxxx

..... (每个xxxx是不同的数字)

我想按行如下排列每一行:

     A         B         C
1| A_xxxx | B_xxxx  | C_xxxx
2| A_xxxx | B_xxxx  | C_xxxx
3| A_xxxx | B_xxxx  | C_xxxx

...

我该怎么做这个请求?

1 个答案:

答案 0 :(得分:0)

此子程序将使用VBA:

Sub SortValsToCols()

Dim w1 As Worksheet
Dim w2 As Worksheet
Dim rCell As Range
Dim rRng As Range
Dim rowCounters As New Scripting.Dictionary
Dim i As Long

Set w1 = Sheets("Sheet1") 'Change to name of the worksheet containing data.
Set w2 = Sheets("Sheet2") 'Change to name of a blank worksheet. The sorted data will end up here.
Set rRng = w1.Range("A1:C3") 'Change to range of cells containing data.

'Turn off ScreenUpdating to speed up execution.
Application.ScreenUpdating = False

'Fills a dictionary with keys from A-Z and gives each an initial value of 1.
For i = 65 To 90
    rowCounters.Add Key:=Chr(i), Item:=1
Next i

'Loops thru all cells in range specified and adds the value after the last populated _
    cell in the relevant column to the target sheet.
For Each rCell In rRng.Cells
    w2.Range(Left$(rCell.Value, 1) & rowCounters(Left$(rCell.Value, 1))).FormulaR1C1 = rCell.Value
    rowCounters(Left$(rCell.Value, 1)) = rowCounters(Left$(rCell.Value, 1)) + 1
Next rCell

'Turn ScreenUpdating back on.
Application.ScreenUpdating = True

End Sub

您需要更改3 SET语句以适合您的工作簿,并在运行之前通过VBE中的Tools-> References添加“Microsoft Scripting Runtime”。

还假设所有单元格值都以?_开头,其中?是来自A-Z的单个大写字母。