我很难尝试对列进行排序。应该是一个简单的修复,但我一直卡住。我的列设置为当它首次填充时,列A可能具有行3 6 9 12中的值,列B可能具有1 2 3 4中的值,C可能具有10 20和30中的值。我正在尝试从A列转到C列,并按字母顺序递归排序。我已经硬编码为子,但每次进入没有值的列时,它都会完全结束程序。这就是我到目前为止所拥有的
ActiveWorkbook.ActiveSheet.AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.AutoFilter.Sort.SortFields.Add Key:= _
Range("G1:G3000"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption _
:=xlSortNormal
With ActiveWorkbook.ActiveSheet.AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ActiveWorkbook.ActiveSheet.AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.AutoFilter.Sort.SortFields.Add Key:= _
Range("H1:H3000"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption _
:=xlSortNormal
With ActiveWorkbook.ActiveSheet.AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ActiveWorkbook.ActiveSheet.AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.AutoFilter.Sort.SortFields.Add Key:= _
Range("I1:I3000"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption _
:=xlSortNormal
With ActiveWorkbook.ActiveSheet.AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ActiveWorkbook.ActiveSheet.AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.AutoFilter.Sort.SortFields.Add Key:= _
Range("J1:J3000"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption _
:=xlSortNormal
With ActiveWorkbook.ActiveSheet.AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
我在两张纸上调用该功能。在第1页上,它的值最多为J,但是在第2页上它只有I值,它会卡在第2页上给我一个错误,因为J上没有任何内容。我如何结合for循环以及我的程序将如何知道如果下一栏中有/不是值?
Column A Column B Column C Column D Column E
Row 1 Bread Fruit
Row 2 Apple OJ Coffee
Row 3 Banana Bread Lotion Water
Row 4 Soda
Row 5 Fruit Coke
Row 6 Coffee Tea
答案 0 :(得分:0)
根据您的描述,这样的事情可能适合您:
Sub tgr()
Dim wb As Workbook
Dim ws As Worksheet
Dim i As Long
Set wb = ActiveWorkbook
For Each ws In wb.Sheets
Select Case ws.Name
Case "Sheet1", "Sheet2"
For i = ws.Columns("A").Column To ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
With ws.Range(ws.Cells(1, i), ws.Cells(ws.Rows.Count, i).End(xlUp))
If .Cells.Count > 1 Then
.Sort .Cells, xlAscending, Header:=xlYes
End If
End With
Next i
End Select
Next ws
End Sub
修改强>
如果您的数据实际上没有标题,请尝试以下方法:
Sub tgr()
Dim wb As Workbook
Dim ws As Worksheet
Dim rLast As Range
Dim i As Long
Set wb = ActiveWorkbook
For Each ws In wb.Sheets
Select Case ws.Name
Case "Sheet1", "Sheet2"
On Error Resume Next
Set rLast = ws.Cells.Find("*", ws.Range("A1"), xlFormulas, , xlByColumns, xlPrevious)
On Error GoTo 0
If Not rLast Is Nothing Then
For i = ws.Columns("A").Column To rLast.Column
With ws.Range(ws.Cells(1, i), ws.Cells(ws.Rows.Count, i).End(xlUp))
If .Cells.Count > 1 Then .Sort .Cells, xlAscending, Header:=xlYes
End With
Next i
End If
End Select
Next ws
End Sub