自定义与VBA中的variablessorting

下面的macros是我logging的自定义sorting。 我用variablesreplace了实际的表名,所以我可以运行这个任何其他表名。 我不希望它是具体的一个名字。 当我运行macros时,我得到一个:

运行时错误“1004”:没有find具有指定名称的项目

当我点击帮助button时,它会将我发送到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 

首先,我注意到,虽然大多数表引用是这样的..ListObjects(TableName).. ,其中一个看起来像这样..ListObjects("TableName")..所以我猜这就是错误的地方来自(哪里。

但是,总的来说,我build议不仅要将表名称放入一个variables中,而且还要将表格名称放入表格中,如下所示:

 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表的列名参数)