首页 文章

Excel VBA用于在单元格中呈现超链接

提问于
浏览
1

我想在VBA for Excel中编写我自己的宏/函数,在Excel中引入一个新的"formula" JIRA(ISSUE_ID) 以便我可以使用

=JIRA("ISSUE_ID")

在单元格中,它呈现以下链接(伪Markdown语法)

[ISSUE_ID](http://my.jira.com/browse/ISSUE_ID)

在同一个单元格中, [ISSUE_ID] 是要在单元格中显示的链接文本, (http://my.jira.com/tracker/ISSUE) 是链接的URL .

这是一个有希望澄清我的需求的例子:

我使用"formula" =JIRA("ABC-1234") 以及我的VBA函数应该做的是,将超链接渲染到包含此公式的同一单元格中,该公式将 ABC-1234 显示为单元格的内容,该单元格是 http://my.jira.com/browse/ABC-1234 的超链接 .

在VBA伪代码中,我的函数写得像这样:

Function JIRA(issue_id)
    current_cell = cell_in_which_this_function_is_used_as_formula()
    url = "http://my.jira.com/browse/" + issue_id
    current_cell.content = issue_id     'text to be shown in the cell
    current_cell.hyperlink = url        'hyperlink to be used for the cell
End Function

我可以用 =HYPERLINK("http://my.jira.com/browse/ISSUE", "ISSUE") 获得相同的结果,但我不想使用2列来实现这一目标(例如 =Hyperlink("http://my.jira.com/" & B1,B1) ) .

3 回答

  • 0

    我不确定这是可能的 . 您只需在工作表更改事件中编写一个子例程,只要在包含TRACKER和ISSUE的列中更新单元格,就可以自动添加 =HYPERLINK("http://my.jira.com/TRACKER/ISSUE", "ISSUE") . 您可以简单地从输入到单元格中的文本构建公式 .

    或者,你可以这样做:

    =Hyperlink("http://my.jira.com/" & A1 & "/" & B1,B1)
    

    假设您的Tracker列位于A列中,而您的Issue列位于B列中 . 拖放公式并自行调整 .

  • 1

    实际上,有一种方法 . 在ThisWorkbook中:

    Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    
        On Error Resume Next
    
        If Target.Cells.Count = 1 Then
            Dim cell As Range
            Set cell = Target.Cells(1, 1)
            If LCase(Left(cell.formula, 5)) = "=jira" Then
                If cell.Hyperlinks.Count > 0 Then
                    cell.Hyperlinks.Delete
                End If
                Dim issue As String
                issue = Evaluate(cell.formula)
                cell.Hyperlinks.Add cell, _
                                    "http://my.jira.com/browse/" & issue, _
                                    issue, _
                                    "Click to view issue " & issue
            End If
        End If
    
    End Sub
    

    在一个模块中

    Public Function Jira(id As String)
        Jira = id
    End Function
    

    JIRA in action

  • 1

    在这里,您可以将值 Issue001 (或任何问题)放在单元格中并运行此代码

    Sub setTheHyperLink()
        Dim lastPart
        Dim theScreenTip
        Dim i
        Dim rngList As Range
        Dim theLink
    
        Set rngList = Selection 'set the range where you have the "Issue"
    
    For Each i In rngList
        lastPart = i.Value
        theScreenTip = lastPart
        theLink = "http://my.jira.com/TRACKER/" & theScreenTip
    
        If i.Hyperlinks.Count > 0 Then
            i.Hyperlinks(1).Address = theLink
            i.Hyperlinks(1).ScreenTip = theScreenTip
            i.Hyperlinks(1).TextToDisplay = theScreenTip
        Else
            i.Hyperlinks.Add _
            Anchor:=i, _
            Address:=theLink, _
            ScreenTip:=theScreenTip, _
            TextToDisplay:=theScreenTip
        End If
    Next i
    

    定义了该单元后,您不需要使用UDF .

相关问题