在不同的表上使用一个宏,独立

时间:2016-12-21 15:45:12

标签: excel vba excel-vba

目标

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

问题

复制工作表时,宏指的是原始工作表上的表格。

当前代码

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

有没有办法以相对方式分配表格?该表始终显示在相同的单元格中,逐页显示。

1 个答案:

答案 0 :(得分:2)

我有3个示例,第一个找到您指定的单元格的表。在这种情况下,您需要将D6中的TableName = ActiveSheet.Range("D6").ListObject.Name更改为表格内的单元格。找到表后,它会在该表上运行过滤器。如果找不到表格,所有3个示例都会抛出一个消息框,如果您不想要它,您可以将其注释掉或删除它。您应该可以将按钮绑定到3中的任何一个并使用它。

我找到了代码来查找表here并修改它以使用您提供的代码。

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

下面的代码将查看您当前选择的单元格,找到与其关联的表格,然后使用该表格运行过滤器。

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

另一个替代方案是下面的代码,它只是在ActiveSheet上找到的第一个表上运行过滤器,所以如果你只有一个表,那么这应该可以正常工作。使用这个,你不需要在运行之前选择表格内的单元格,但如果每张表格有多个表格,则可能需要使用上述代码。

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