excel - VBA:使用宏对工作表进行排序

标签 excel vba sorting

如图所示

This is a picture of the error

我的排序语法错误,我不明白为什么。

我明白了

Run-time error '1004': The sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort By box isn't the same or blank.

Sub Sort()
'
' Sort Macro

Dim rowNum As Variant

Dim columnNum As Variant
Dim sortField As Range
Dim keySort As Range

rowNum = Worksheets("Updated 1.0").Range("A1").End(xlDown).row
MsgBox (rowNum)

columnNum = Worksheets("Updated 1.0").Range("A1").End(xlToRight).column
MsgBox (columnNum)

With Worksheets("Updated 1.0")
    Set sortField = Range(.Cells(2, 1), .Cells(rowNum, columnNum))
    Set keySort = Range("A1")
    sortField.Sort Key1:=keySort, Order1:=xlDescending, MatchCase:=False, 
Orientation:=xlSortRows

End With

最佳答案

您在 With 中缺少一些 .,但我认为排序也不正确。

这对我有用:

Sub Sort()

    Dim sht As Worksheet
    Dim sortField As Range
    Dim keySort As Range

    Set sht = Worksheets("Updated 1.0")

    With sht
        Set sortField = .Range("A1").CurrentRegion
        Set keySort = .Range("A1")
        sortField.Sort Key1:=keySort, Order1:=xlDescending, MatchCase:=False, _
                       Orientation:=xlSortRows
    End With

End Sub

关于excel - VBA:使用宏对工作表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53397975/

相关文章:

excel - 比较两个 Excel 工作表

c# - 考虑数字的字符串比较

excel - 如何在支付期结束后找到下一个星期五

excel - Powershell Excel 自动化 - 计划任务中的保存/打开失败

javascript - EXCEL VBA HTML 单击按钮,然后单击下拉选项

python - 如何在python中自定义排序列表

sorting - 在 F# 中对元组内的值进行排序

java - 在 getCellFormula 中获取结果

java - java导入xlsx批量数据

VBA 展望。尝试从电子邮件正文中提取特定数据并导出到 Excel