Excel VBA用于渲染单元格中的超链接

我想在VBA for Excel中编写自己的macros/函数,在Excel中引入一个新的“公式” 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。

这是一个例子,希望能够澄清我的需求:

我使用“公式” =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) )。

我不确定这是可能的。 你可以直接在工作表变更事件中写一个子程序来自动添加=HYPERLINK("http://my.jira.com/TRACKER/ISSUE", "ISSUE") ,只要在持有TRACKER和问题。 您可以简单地从input到单元格中的文本中构build公式。

或者,你可以这样做:

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

假设您的Tracker列在A列,您的Issue列在B列。拖放公式,它会自动调整。

其实有一个办法 在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在行动

在这里,您可以将值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。