2016-12-21 4 views
0

목표서로 다른 테이블에 하나의 매크로 사용 독립적으로

셀 값을 기반으로 테이블에서 자동 필터를 실행하는 버튼입니다.

문제

시트를 복제, 매크로 원반의 테이블을 참조한다.

현재 코드

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

상대 방식으로 테이블을 할당하는 방법이 있나요? 표는 항상 같은 셀에 시트별로 나타납니다.

답변

2

나는 당신에게 3 가지 예제를 가지고 있는데, 첫번째는 당신이 지정한 셀에 대한 테이블을 찾는다. 이 경우 TableName = ActiveSheet.Range("D6").ListObject.NameD6을 테이블 안의 셀로 변경해야합니다. 테이블을 찾은 후 해당 테이블에서 필터를 실행합니다. 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 
관련 문제