学习目标:
VBA自定义函数实习单元格超链接到单元格的功能
学习内容:
掌握自定义函数设计与调用
掌握数组的动态单元格赋值语法
掌握vba超链接语句的格式用法
学习时间:
2023年12月1日
学习产出:
自定义函数模块hyper(name1 As String, name2 As String)
具体代码:
Sub 单元格超链接到单元格()
Dim name1 As String, name2 As String
name1 = "Sheet1" '字符加双引号
name2 = "数据源"
Call hyper(name1, name2) '调用无返回值的函数
End Sub
Function hyper(name1 As String, name2 As String)
'自定义函数实现超链接到单元格
'===========
'@Author LAUWINGKUI
'@Date 2023/12/01
'===========
Dim sht1, sht2
Dim irow1, irow2
Dim arr, brr
Dim str As String
Set sht1 = Worksheets(name1) '引用字符变量不用加双引号
Set sht2 = Worksheets(name2)
irow1 = sht1.[b65536].End(3).Row '获取最大行号
arr = sht1.Range("B1:B" & irow1).Value '这种方式赋值数组不需要redim
irow2 = sht2.[b65536].End(3).Row
brr = sht2.Range("B1:B" & irow2).Value
For i = 2 To UBound(arr)
For j = 2 To UBound(brr)
If arr(i, 1) = brr(j, 1) And brr(j, 1) <> "" Then
str = arr(i, 1)
sht1.Hyperlinks.Add Anchor:=Cells(i, 2), Address:="", SubAddress:= _
sht2.Name & "!" & Cells(j, 2).Address(0, 0), TextToDisplay:=str
'参数Anchor表示要操作的单元格
'参数Address表示超链接的地址
'参数SubAddress表示字地址,引用表示单元格时注意格式
'参数TextToDisplay表示需要显示的字符
End If
Next
Next
End Function