独立地在不同的表上使用一个macros

目标

基于单元值在表上执行自动筛选的button。

问题

复制表单时,macros指向原始表单上的表格。

当前代码

Sub Macro1() ActiveSheet.ListObjects("Table33").Range.AutoFilter Field:=6, Criteria1:=">" & Range("K9").Value End Sub 

有没有办法以相对的方式分配一个表? 表格总是出现在同一个单元格中,一张张一张。

我有3个例子,第一个find你指定单元格的表。 在这种情况下,您需要将TableName = ActiveSheet.Range("D6").ListObject.NameD6更改为表格中的单元格。 find表后,它运行该表上的filter。 如果没有find表格,所有3个示例都会抛出一个消息框,如果不需要,可以对其进行注释或删除。 你应该能够将你的button绑定到3中的任何一个并使用它。

我发现代码在这里find表,并修改它以使用您提供的代码。

 Sub RangeTable() Dim TableName As String Dim ActiveTable As ListObject 'Determine if ActiveCell is inside a Table On Error GoTo NoTableSelected TableName = ActiveSheet.Range("D6").ListObject.Name 'Change range to cell inside of table Set ActiveTable = ActiveSheet.ListObjects(TableName) On Error GoTo 0 'Do something with your table variable (ie Add a row to the bottom of the ActiveTable) ActiveTable.Range.AutoFilter Field:=6, Criteria1:=">" & Range("K9").Value Exit Sub 'Error Handling NoTableSelected: MsgBox "There is no Table currently selected!", vbCritical End Sub 

下面的代码将查看您当前select的单元格,find与之关联的表格,然后使用该表格运行filter。

 Sub ActiveTable() Dim SelectedCell As Range Dim TableName As String Dim ActiveTable As ListObject Set SelectedCell = ActiveCell 'Determine if ActiveCell is inside a Table On Error GoTo NoTableSelected TableName = SelectedCell.ListObject.Name Set ActiveTable = ActiveSheet.ListObjects(TableName) On Error GoTo 0 'Do something with your table variable (ie Add a row to the bottom of the ActiveTable) ActiveTable.Range.AutoFilter Field:=6, Criteria1:=">" & Range("K9").Value Exit Sub 'Error Handling NoTableSelected: MsgBox "There is no Table currently selected!", vbCritical End Sub 

另一种select是下面的代码只运行在ActiveSheet上find的第一个表上的filter,所以如果你只有一个表,那么这应该工作正常。 有了这个,你不需要在运行它之前select一个表格中的单元格,但是如果你有多个表格,你可能需要使用上面的代码。

 Sub SheetTable() Dim TableName As String Dim ActiveTable As ListObject 'Determine if ActiveCell is inside a Table On Error GoTo NoTableSelected TableName = ActiveSheet.ListObjects.Item(1) Set ActiveTable = ActiveSheet.ListObjects(TableName) On Error GoTo 0 'Do something with your table variable (ie Add a row to the bottom of the ActiveTable) ActiveTable.Range.AutoFilter Field:=6, Criteria1:=">" & Range("K9").Value Exit Sub 'Error Handling NoTableSelected: MsgBox "There is no Table currently selected!", vbCritical End Sub