VBA - 按升序日期排序表

时间:2017-11-06 12:35:58

标签: vba excel-vba excel

我有以下代码,我想按升序日期订购表格:

Set TableCreated = ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$8:$F$22"), , xlNo)
TableCreated.Name = matchCheck
With TableCreated.Sort
        .SortFields.Add Key:= _
            Range("[[#All],[Column1]]"), _
            SortOn:=xlSortOnValues, _
            Order:=xlAscending, _
            DataOption:=xlSortNormal
End With

但是代码失败了。 我试图通过录制宏找到解决方案并检查代码:

ActiveWorkbook.Worksheets("T1_Migration_C5_BKO").ListObjects( _
    "T1_Migration_C5_BKO").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("T1_Migration_C5_BKO").ListObjects( _
    "T1_Migration_C5_BKO").Sort.SortFields.Add Key:=Range( _
    "T1_Migration_C5_BKO[[#All],[Column1]]"), SortOn:=xlSortOnValues, Order:= _
    xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("T1_Migration_C5_BKO").ListObjects( _
    "T1_Migration_C5_BKO").Sort
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply

这里的问题是该表是由name而不是参数TableCreated调用的。

谢谢,

迈克尔

2 个答案:

答案 0 :(得分:0)

你能尝试这样做:

With ActiveWorkbook.Worksheets("T1_Migration_C5_BKO").ListObjects(TableCreated.Name).Sort

因此,该表将通过其名称来调用,例如TableCreated.Name。它应该工作。

答案 1 :(得分:0)

由于您正在为表命名,请在范围参数中使用该名称:

Set TableCreated = ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$8:$F$22"), , xlNo)

matchCheck = "MyTable"
TableCreated.name = matchCheck

With ActiveSheet.ListObjects(matchCheck).Sort
    .SortFields.Add Key:= _
        Range(matchCheck & "[Column1]"), _
        SortOn:=xlSortOnValues, _
        Order:=xlAscending, _
        DataOption:=xlSortNormal
    .Apply
End With

另外,不要忘记.Apply!