问题描述
我在工作簿中有单元格链接到(单独)命名的单元格。单元格名称都以“Filter”开头,然后是一些字符串(例如 FilterSubcategory1”)。
如果用户点击其中一个链接,它会将它们带到链接的单元格,然后根据目标所在的位置过滤另一个工作表(目前使用 .Address
,一切正常)。由于它们的名称中都有相同的起始字符串,如果目标名称以“Filter”开头,是否可以进行过滤?这将使我的代码更短,而不是列出所有相关的命名范围。
它看起来像这样(出于说明目的,不是我的完整或优化代码):
If Target.Range.Name = "Filter" & "*" Then
'rest of code,do the filtering
End If
或:
If InStr(Target.Range.Name,"Filter") > 0 Then
'rest of code,do the filtering
End If
解决方法
请尝试下一个功能:
Function IsFilter(cel As Range) As Boolean
If cel.Hyperlinks.Count = 0 Then Exit Function
If InStr(cel.Hyperlinks.SubAddress,"Filter") > 0 Then IsFilter = True
End Function
上面的函数可以在下面的方式中使用:
Sub testIsFilter()
Dim testCell As Range
Set testCell = ActiveCell 'it may be any cell (resulted from a iteration or not)
If IsFilter(testCell) Then
'rest of code,do the filtering
End If
End Sub
请测试并发送一些反馈。
,因此,在尝试了其他用户的解决方案后(对解决方案非常有帮助),我设法以不同的方式解决了它。一些超链接链接到自己(实际上,所有过滤器都链接),一些链接到合并的单元格,所以这是我用于链接到自己的任何单元格的方法:
FltrStr = "='" & ActiveSheet.Name & "'!" & ActiveCell.Address 'builds up the cell address from scratch,allowing for a merged cell being selected
Set FltrRng = Range(FltrStr) 'converts the string into the actual range needed,important for the next line
FltrName = FltrRng.Name.Name 'gets the name of the range,reporting the given name if it exists,lookup .name.name if you are unsure why two .names are needed
然后我可以使用它来检查目标范围是否具有以我想要的任何开头的名称,此处为“过滤器”:
If InStr(FltrName,"Filter") > 0 Then
'rest of code,do the filtering
End If
可能不是最漂亮/最有效的方法,但它确实有效。可能值得在 sub 的开头明确定义变量的类型(FltrStr、FltrRng、FltrName)以避免任何类型不匹配错误,但我目前还没有定义它们并且它们工作正常。 (不好的做法,我知道!)