我记录了一个宏,并在一个页面上对一个表进行排序,它分配了一个页面名称,我想将其设置为变量,以便在活动页面上执行相同的操作。
我有一个反映页面名称的命名单元格,并尝试将其放入页面中,但一直出现错误。
只需尝试用代表活动页面的变量替换(“ TRADE”)
ActiveWorkbook.Worksheets("TRADE").ListObjects("Table4").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("TRADE").ListObjects("Table4").Sort.SortFields.Add _
Key:=Range("Table4[[#All],[Column2]]"), SortOn:=xlSortOnValues, Order:= _
xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("TRADE").ListObjects("Table4").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ActiveWorkbook.Worksheets("TRADE").ListObjects("Table6").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("TRADE").ListObjects("Table6").Sort.SortFields.Add _
Key:=Range("Table6[[#All],[Column2]]"), SortOn:=xlSortOnValues, Order:= _
xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("TRADE").ListObjects("Table6").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
答案 0 :(得分:1)
这是未经测试的,但是要替换它...
ActiveWorkbook.Worksheets("TRADE")
...与此...
ActiveSheet
(当我说“未经测试”时,我的意思是ActiveSheet是否应该在上下文中存在,无论它在您更改的所有代码中是否均能正常工作,这是另一回事,这只是对我的回答的警告。)
答案 1 :(得分:1)
Skin给您的答案可能是最好的方法,但这是另一种选择:用一个变量替换硬编码名称,就像这样...
Dim wks As Worksheet
Set wks = ActiveSheet
然后,您需要用wks.Name
替换工作表名称的每个瞬间。您的代码如下所示:
Dim wks As Worksheet
Set wks = ActiveSheet
ActiveWorkbook.Worksheets(wks.Name).ListObjects("Table4").Sort.SortFields.Clear
ActiveWorkbook.Worksheets(wks.Name).ListObjects("Table4").Sort.SortFields.Add _
Key:=Range("Table4[[#All],[Column2]]"), SortOn:=xlSortOnValues, Order:= _
xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets(wks.Name).ListObjects("Table4").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ActiveWorkbook.Worksheets(wks.Name).ListObjects("Table6").Sort.SortFields.Clear
ActiveWorkbook.Worksheets(wks.Name).ListObjects("Table6").Sort.SortFields.Add _
Key:=Range("Table6[[#All],[Column2]]"), SortOn:=xlSortOnValues, Order:= _
xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets(wks.Name).ListObjects("Table6").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub