1

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

运行时错误“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
4

1 回答 1

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

(注意:更正了换行符)


(注:修正范围表列名参数)

于 2013-10-23T15:41:35.310 回答