自定义使用VBA中的变量排序

时间:2013-10-23 15:21:45

标签: excel excel-vba sorting vba

下面的宏是我录制的自定义排序。我用变量替换了实际的表名,所以我可以为任何其他表名运行它。我不希望它特定于一个名字。当我运行宏时,我得到了一个:

  

运行时错误“1004”:找不到具有指定名称的项目

当我点击帮助按钮时,它会将我发送到Excel帮助菜单。 你能让我知道我错过了什么吗? 如果可能的话,有一种方法可以缩短我的代码。我知道录音可能很长。

**注意所有这些都在表格中

Dim sh As Worksheet
Dim TableName As String

 Set sh = ActiveSheet
 TableName = sh.Name


    ActiveWorkbook.Worksheets(TableName).ListObjects(TableName).sort. _
      SortFields.Clear
    ActiveWorkbook.Worksheets(TableName).ListObjects(TableName).sort. _
      SortFields.Add Key:=Range(TableName, [BEVEL]), SortOn:=xlSortOnValues,
      Order:=xlAscending, _
      CustomOrder:="BEVEL_YES_MITER,BEVEL_NO_RADIUS", DataOption:=xlSortNormal _

    ActiveWorkbook.Worksheets(TableName).ListObjects("TableName").sort. _
      SortFields.Add Key:=Range(TableName, [MATERIAL]), SortOn:=xlSortOnValues, _
      Order:=xlAscending, DataOption:=xlSortNormal
    ActiveWorkbook.Worksheets(TableName).ListObjects(TableName).sort. _
      SortFields.Add Key:=Range(TableName, [Length]), SortOn:=xlSortOnValues, _
      Order:=xlDescending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets(TableName).ListObjects(TableName).sort
      .Header = xlYes
      .MatchCase = False
      .Orientation = xlTopToBottom
      .SortMethod = xlPinYin
      .Apply
     End With
Selection.AutoFilter
End Sub

1 个答案:

答案 0 :(得分:1)

首先,我注意到虽然您的大多数表格引用都与..ListObjects(TableName)..类似,但其中一个看起来像..ListObjects("TableName")..,所以我猜错了错误所在来自。

但是,一般情况下,我建议不仅将表名放入变量,还要将表本身放入表中,如下所示:

Dim sh As Worksheet
Dim TableName As String
Dim theTable As ListObject

 Set sh = ActiveSheet
 TableName = sh.Name
 Set theTable = ActiveWorkbook.Worksheets(TableName).ListObjects(TableName)

    theTable.sort.SortFields.Clear
    theTable.sort.SortFields.Add _
      Key:=Range(TableName & "[BEVEL]"), SortOn:=xlSortOnValues,
      Order:=xlAscending, _
      CustomOrder:="BEVEL_YES_MITER,BEVEL_NO_RADIUS", DataOption:=xlSortNormal 

    theTable.sort.SortFields.Add 
      Key:=Range(TableName & "[MATERIAL]"), SortOn:=xlSortOnValues, _
      Order:=xlAscending, DataOption:=xlSortNormal
    theTable.sort.SortFields.Add  _
      Key:=Range(TableName & "[Length]"), SortOn:=xlSortOnValues, _
      Order:=xlDescending, DataOption:=xlSortNormal
    With theTable.sort
      .Header = xlYes
      .MatchCase = False
      .Orientation = xlTopToBottom
      .SortMethod = xlPinYin
      .Apply
     End With
Selection.AutoFilter
End Sub

(注意:纠正了换行符)


(注意:更正了Range表 - 列名参数)