简体   繁体   中英

Using VBA in Excel to sort a table without the table's name

My goal is to create macro whose purpose is simply to sort a table in ascending order. I know it seems like a lot of work to save a couple of clicks, but I need it as part of a larger macro, the rest of which already works. Using the record function, I got this.

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

The above code does work, but I would like to do this without having to reference the table name specifically, because that may change depending on where I'm using it. I wanted to use something like this

Sheets("Sheet1").ListObjects(1).ListColumns(1).Range

which as far as I can tell, should point to the same range as Table1[[#All],[Column1]] , but VBA doesn't like it. It errors out with "object doesn't support this property or method". I'm fairly confident in using ListObjects(1) because there should only ever be one table on the sheet.

  1. What am I doing wrong?
  2. Is Sheets("Sheet1").ListObject(1).ListColumns(1).Range equivalent to Table1[[#All],[Column1]] ?
  3. Is there an easier way to sort a table using VBA?

Update: Thanks Chris for the answer; and, I also realized later that I could just rename the table at the start of the script and avoid this whole mess.

Tested this, it works provided Table1 is the first or only ListObject on the sheet, and Column1 is the first column

Sub Demo()
    With ActiveWorkbook.Worksheets("Sheet1").ListObjects(1).Sort
        .SortFields.Clear
        .SortFields.Add _
          Key:=Sheets("Sheet1").ListObjects(1).ListColumns(1).Range, _
          SortOn:=xlSortOnValues, _
          Order:=xlAscending, _
          DataOption:=xlSortNormal
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM