【问题标题】:vba sort and filter using range objectsvba 使用范围对象进行排序和过滤
【发布时间】:2018-05-13 19:45:06
【问题描述】:

我有数据需要对多列进行排序,然后按 0/1 过滤,我想简单地使用任何工作表并找到我已经完成的列地址:

Dim ColName1 As Variant
Set ColName1 = sht.Cells.Find("name of column").Address

我可以将它用于排序命令的一部分,但我正在尝试设置另一个 Varient 或 String = Left(sht.Cells.Find("name of column").Address,2) 删除 $1从 $K$1 但是当输入到排序命令时,它不喜欢它。我需要使用其他类型来定义 ColName1 吗?或者将第二个项目定义为 int/其他东西?

ActiveWorkbook.Worksheets("test").sort.SortFields.Add Key:=Range(ColName1.Address & ":K" & LastRow) _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal          'categ / material
With ActiveWorkbook.Worksheets("test").sort
        .SetRange Range(UsedRange)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

我有多个列要排序,所以我想让它动态化,并最终将其放入一个界面,我只需在其中读取文件并使用用户定义的变量/对象来定义要排序的列。

此外,我阅读了很多关于不引用当前 ActiveWorkbook.Worksheets 的内容,但是当我尝试定义类似

的内容时
Set sht = ActiveSheet

它只适用于某些事情,但不适用于 sht.sort ??我错过了什么......

【问题讨论】:

    标签: vba sorting autofilter


    【解决方案1】:

    在 VBA 中进行排序非常痛苦。以下是我的处理方法:

    Sub TestSort()
    
    Dim Sht As Worksheet
    Dim SortCol  As Long
    Dim LastRow As Long
    Dim LastCol As Long
    
    Set Sht = ActiveSheet
    LastRow = Cells(Rows.Count, 1).End(xlUp).Row
    LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
    SortCol = Sht.Cells.Find("Name of Column").Column
    Sht.Sort.SortFields.Clear
    Sht.Sort.SortFields.Add Key:=Range(Cells(2, SortCol), Cells(LastRow, SortCol))
    With Sht.Sort
        .SetRange Range(Cells(1, 1), Cells(LastRow, LastCol))
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2015-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多