基于ActiveCell值(VBA)过滤表的动态超链接

时间:2016-11-29 23:30:01

标签: excel vba excel-vba

我正在创建一个动态超链接,用于过滤另一张表格上的表格(Sheet15)。

我的目标是让用户能够在Sheet3上选择一个单元格,并将此单元格的VALUE作为另一个工作表上的过滤器。

到目前为止,这是我的代码:

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    If Target.Type = msoHyperlinkRange And Target.Range.Address = "$S$15" Then
        Application.ScreenUpdating = False
        Sheet15.Visible = True
        Sheet15.ListObjects("Table17").Range.AutoFilter Field:=19, Criteria1:=ActiveCell.Value
        Sheet15.Activate
        Application.ScreenUpdating = True
    End If
End Sub

然而,当我点击超链接时,表格根本没有被过滤,所以我必须做错事。

有人可以帮忙吗?

更新

这是更新的代码。

单元格S17现在是我想要将表格过滤到的值:

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    If Target.Type = msoHyperlinkRange And Target.Range.Address = "$S$15" Then
        Application.ScreenUpdating = False
        Sheet15.Visible = True
        Sheet15.ListObjects("Table17").Range.AutoFilter Field:=19, Criteria1:=Sheet3.Range("S17").Value
        Sheet15.Activate
        Application.ScreenUpdating = True
    End If
End Sub

但问题仍然存在。当我点击它们的超链接时,我将被带到另一张表,但该表根本没有被过滤。

2 个答案:

答案 0 :(得分:1)

注意:除非超链接指向自身,ActiveCell.Value将是链接目标值:如果您想要包含链接的单元格中的值,请使用Target.Range.Value

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    If Target.Type = msoHyperlinkRange And Target.Range.Address = "$S$15" Then
        Application.ScreenUpdating = False
        With Sheet15
            .Visible = True
            .ListObjects("Table17").Range.AutoFilter Field:=19, _
                                     Criteria1:=Target.Range.Value
            .Activate
        End With
        Application.ScreenUpdating = True
    End If
End Sub

答案 1 :(得分:1)

坚持原来的计划,并假设专栏" A"是具有城市名称的名称,将以下内容放在工作表代码窗格

Option Explicit

Dim lastCell As Range '<--| declare a module scoped range variable to store the last cell selected by the user, if "valid"

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Address = "$S$15" Then Exit Sub '<-- do nothing if user selected cell with hyperlink
    Set lastCell = Intersect(Target, Columns("A")) '<-- change "Columns("A") to a named range with your cities
End Sub

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    If lastCell Is Nothing Then Exit Sub '<--| no action if lastCell has not been properly set by 'Worksheet_SelectionChange()'

    If Target.Type = msoHyperlinkRange And Target.Range.Address = "$S$15" Then
        Application.ScreenUpdating = False
        Sheet15.Visible = True
        Sheet15.ListObjects("Table17").Range.AutoFilter Field:=19, Criteria1:=lastCell.Value '<--| set the criteria as 'lastCell' value
        Sheet15.Activate
        Application.ScreenUpdating = True
    End If
End Sub

根据评论,您可以将Columns("A")中的Worksheet_SelectionChange()引用更改为城市名称的实际范围(可能是命名范围