用与HYPERLINK链接的颜色突出显示目标单元格

时间:2018-12-30 03:40:18

标签: python excel openpyxl

我实现了一项功能,其中在几行之间有动态超链接。这些超链接指向同一工作簿中不同工作表中的不同单元格。当我单击任何超链接时,我可以导航到该目标单元格。

现在,默认情况下,该单元格以黑色粗框突出显示。在单击HYPERLINK之后,只要突出显示该单元格,我有什么方法可以使该单元格显示为特定颜色。

1 个答案:

答案 0 :(得分:1)

大问题!我们可以使用工作表事件来处理。我认为适合使用的事件是关注超链接事件。说实话,不确定如何通过python进行设置。但是无论如何还是很有趣的!祝你好运。

代码如下:

该事件本身,在包含您的超链接的工作表中:

Option Explicit

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    AlterHyperLinkedRanged.Main Target
End Sub

常规模块名为 AlterHyperLinkedRanged

Option Explicit

Sub Main(Target As Hyperlink)

    Dim ParsedSubAddress As ParsedSubAddress
    Set ParsedSubAddress = New ParsedSubAddress

    ParsedSubAddress.Parse Target.Subaddress

    Dim HyperLinkedRange As Range
    Set HyperLinkedRange = ParsedSubAddress.Worksheet.Range(ParsedSubAddress.Address)

    HyperLinkedRange.Borders.Color = RGB(0, 255, 0)

End Sub

我们创建的类用于存储由target.subaddress使用的数据,也就是我们要更改其边界的范围。我创建了一个新对象来处理解析和存储此数据。我正在即时执行此操作,请随时改进!这段代码将放在类模块中。

名为 ParsedSubAddress 的类:

Option Explicit

Private Type Attrib
    Address As String
    WS As Worksheet
End Type

Private this As Attrib

Public Property Get Address() As String
    Address = this.Address
End Property

Private Property Let Address(value As String)
    this.Address = value
End Property

Public Property Get Worksheet() As Worksheet
    Set Worksheet = this.WS
End Property

Private Property Let Worksheet(value As Worksheet)
    this.WS = value
End Property

Function Parse(ByVal Subaddress As String)
    If Not (InStr(Subaddress, "!") > 0) Then
        this.Address = Subaddress
        Set this.WS = ActiveSheet
    Else
        this.Address = Mid(Subaddress, InStr(Subaddress, "!") + 1, Len(Subaddress))
        Set this.WS = Sheets(Mid(Subaddress, 1, InStr(Subaddress, "!") - 1))
    End If
End Function