我在 Excel 中编写了一个 VBA 宏,以升序水平对一行数字进行排序,然后移动到下一行并重复该过程,直到它遇到空单元格/非数字数据,因为这不是 Excel 的标准功能.
数据为73行7列,数量不超过50。
该代码适用于名为“Sheet1”的工作表的一个电子表格文件,但是,如果“范围”维度指向任何其他工作表,则该宏在其中不起作用。
Sub SortAndMove()
Dim rng As Range
' Set the initial range to the second row, columns A to F
Set rng = Worksheets("Sheet1").Range("A1:G1")
' Loop until the first cell in the current row is not a number or is <= 0
Do While IsNumeric(rng.Cells(1, 1).Value) And rng.Cells(1, 1).Value > 0
' Sort the selected range horizontally in ascending order
rng.Sort Key1:=rng.Cells(1, 1), Order1:=xlAscending, Header:=xlNo
' Move the selection down one row
Set rng = rng.Offset(1, 0).Resize(, 7) ' Resize to select the first six columns
Loop
End Sub
新代码本质上是相同的,除了不同的子例程名称和添加计数器之外:
Sub HorizontalSort()
Dim rng As Range
Dim counter As Range
Dim i As Integer
' Set the initial range to the second row, columns A to G
Set rng = Worksheets("Sheet1").Range("A1:G1")
' Sets the range where the counter will be updated on the worksheet
Set counter = Worksheets("Sheet1").Range("I1")
i = 0
' Loop until the first cell in the current row is not a number or is <= 0
Do While IsNumeric(rng.Cells(1, 1).Value) And rng.Cells(1, 1).Value > 0
' Sort the selected range horizontally in ascending order
rng.Sort Key1:=rng.Cells(1, 1), Order1:=xlAscending, Header:=xlNo
' Move the selection down one row
Set rng = rng.Offset(1, 0).Resize(, 7) ' Resize to select the first seven columns
' Increment the counter and print it's value during each iteration of the loop
i = i + 1
counter.Value = i
Loop
End Sub
我有:
任何人都可以看到我的代码有什么问题,或者想出为什么这行不通的原因吗?
我可以解决这个问题,但可以在有效的工作表中对数据进行排序,但这很烦人,而且不是重点。
示例(测试)
Sub HorizontalSort()
' Set the workbook.
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Set the worksheet.
Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
' Set the range (`A1:GlastRow`).
Dim rg As Range: Set rg = RefRangeFind(ws, "A1:G1")
' Sort the range.
SortRows rg
End Sub
帮助:参考
Function RefRangeFind(ByVal ws As Worksheet, ByVal FirstRow As String) As Range
With ws.Range(FirstRow)
Dim lcell As Range: Set lcell = .Resize(ws.Rows.Count - .Row + 1) _
.Find("*", , xlValues, , xlByRows, xlPrevious)
If lcell Is Nothing Then Exit Function ' no data
Set RefRangeFind = .Resize(lcell.Row - .Row + 1)
End With
End Function
帮助:排序
Sub SortRows(ByVal rg As Range)
If rg Is Nothing Then Exit Sub
Dim rrg As Range
For Each rrg In rg.Rows
rrg.Sort rrg, xlAscending, , , , , , xlNo, , , xlSortRows
Next rrg
End Sub