用链接到超链接的颜色突出显示目标单元格

2022-04-07 00:00:00 python excel openpyxl

问题描述

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

现在,默认情况下,该单元格以粗黑边框突出显示。有没有办法使该单元格在单击超链接后高亮显示时以特定颜色显示。


解决方案

大问题!我们可以使用工作表事件来处理此问题。我觉得适合使用的事件是跟随HYPERLINK事件。老实说,我不知道如何通过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

和我们创建的用来存储目标使用的数据的类。子地址,也就是我们希望更改其边界的区域。我创建了一个新对象来处理、解析和存储这些数据。我正在忙着做这件事,请随意改进!此代码将放入类模块中。

命名的类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

相关文章