要查找通过公式添加的所有超链接,您可以使用 VBA 中的查找功能。以下例程将遍历所有超链接公式并调用子例程“replaceHyperlink”:
Sub replaceHyperlinks(Optional ws As Worksheet = Nothing)
If ws Is Nothing Then Set ws = ActiveSheet
Dim firstHit As Range, hit As Range
Set hit = ws.Cells.Find(What:="=Hyperlink", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
Do While Not hit Is Nothing
Call replaceHyperlink(hit)
Set hit = ws.Cells.FindNext(after:=hit)
Loop
End Sub
现在有点棘手了,我们需要创建一个函数来从Hyperlink-formula 中获取地址(url)和文本。获取文本很容易,您可以使用Value2-property 获取它。对于地址,我想除了分析公式文本之外别无他法。以下例程针对 3 种简单情况执行此操作:
- url 用引号引起来 ("https\\www.stackoverflow.com")
- url 是单元格引用(指向同一张表),例如B2。
- url 是对另一张表的单元格引用(例如Sheet2!B2)
如果 url 本身是由公式创建的(例如 "https:\\" & B2),它将失败。
拥有 URL 和文本,单元格的公式将被替换为文本并创建一个真正的超链接:
Sub replaceHyperlink(cell As Range)
Const FormulaStart = "=HYPERLINK("
If UCase(Left(cell.formula, Len(FormulaStart))) <> FormulaStart Then Exit Sub
Dim formula As String, url As String, p As Long, text As String
' Search for the link address
formula = Mid(cell.formula, Len("=Hyperlink(") + 1)
p = InStr(formula, ",")
If p > 0 Then
formula = Left(formula, p - 1)
Else
formula = Left(formula, Len(formula) - 1)
End If
If Left(formula, 1) = """" And Right(formula, 1) = """" Then
url = Mid(formula, 2, Len(formula) - 2)
ElseIf InStr(formula, "!") = 0 Then
url = cell.Parent.Range(formula)
Else
url = Evaluate(formula)
End If
text = cell.Value2
cell.Value = text
cell.Hyperlinks.Add Anchor:=cell, Address:=url, textToDisplay:=text
End Sub
更新
如果获取 url 的公式比较复杂,也许你可以把这个公式部分暂时写到单元格中。之后,Value2-property 应该将公式解析为 url。将最后几行替换为
text = cell.Value2 ' Save the friendly text
cell.formula = "=" & formula ' Write the URL-part temporarily into cell as formula
url = cell.Value2 ' Get the result of that temp. formula
cell.Value = text
cell.Hyperlinks.Add Anchor:=cell, Address:=url, textToDisplay:=text