久经考验
假设
我在这里介绍了 3 个场景,如 Excel 文件中所示。
=HYPERLINK("www."&"Google"&".Com","Google")
. 这个超链接有一个好记的名字
www.Google.com
普通超链接
=HYPERLINK("www."&"Google"&".Com")
此超链接没有友好名称
截屏:
逻辑:
- 检查它是什么样的超链接。如果它不是具有友好名称的,那么代码非常简单
- 如果超链接有一个友好的名称,那么代码尝试做的是从中提取文本
"www."&"Google"&".Com"
,=HYPERLINK("www."&"Google"&".Com","Google")
然后将其作为公式存储在该单元格中
- 一旦公式将上述文本转换为普通超链接,即没有友好名称,我们就可以使用它打开它
ShellExecute
- 重置单元格的原始公式
代码:
Private Declare Function ShellExecute _
Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hWnd As Long, ByVal Operation As String, _
ByVal Filename As String, Optional ByVal Parameters As String, _
Optional ByVal Directory As String, _
Optional ByVal WindowStyle As Long = vbMinimizedFocus _
) As Long
Sub Sample()
Dim sFormula As String
Dim sTmp1 As String, sTmp2 As String
Dim i As Long
Dim ws As Worksheet
'~~> Set this to the relevant worksheet
Set ws = ThisWorkbook.Sheets(1)
i = 1
With ActiveSheet
Do While WorksheetFunction.IsText(.Range("E" & i))
With .Range("E" & i)
'~~> Store the cells formula in a variable for future use
sFormula = .Formula
'~~> Check if cell has a normal hyperlink like as shown in E2
If .Hyperlinks.Count > 0 Then
.Hyperlinks(1).Follow
'~~> Check if the cell has a hyperlink created using =HYPERLINK()
ElseIf InStr(1, sFormula, "=HYPERLINK(") Then
'~~> Check if it has a friendly name
If InStr(1, sFormula, ",") Then
'
' The idea here is to retrieve "www."&"Google"&".Com"
' from =HYPERLINK("www."&"Google"&".Com","Google")
' and then store it as a formula in that cell
'
sTmp1 = Split(sFormula, ",")(0)
sTmp2 = "=" & Split(sTmp1, "HYPERLINK(")(1)
.Formula = sTmp2
ShellExecute 0, "Open", .Text
'~~> Reset the formula
.Formula = sFormula
'~~> If it doesn't have a friendly name
Else
ShellExecute 0, "Open", .Text
End If
End If
End With
i = i + 1
Loop
End With
End Sub