在超链接地址

时间:2016-12-07 15:12:19

标签: excel vba excel-vba excel-2013

我想从单元格A2中获取值,并将其用作我的VBA的超链接地址。例如,让我们说单元格A2的值为Pink,我想链接到工作表Pink!A1。我遇到的问题是我收到错误

  

语法错误

为了使语法有效,应如何改变?

Dim lr As Long, i As Long
lr = Cells(Rows.Count, 2).End(xlUp).Row
For i = 2 To lr
  ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:=Cells(i, 2).Value"!A1"
Next i

修改
为清楚起见,我想补充一点,我希望链接放在列O中,当前单元格值为列O,但链接到的工作表应该是列B的值。

编辑2
使用@Jeremy建议的语法让我更接近,我就在这一点上,我发现问题是任何特殊符号(即逗号,句号,连字符等)必须用单引号括起来。这留下我的语法在下面,但得到一个错误

  

无效的过程调用或参数

我认为我已经接近完美,但并不完全存在:

Function TakeTwo()
Dim lr As Long, i As Long
Dim sSheet As String
Dim ws As Worksheet

Set ws = ActiveSheet
lr = Cells(Rows.Count, 2).End(xlUp).Row
For i = 2 To lr
  If ws.Cells(i, 2).Value Like "*,*" Or ws.Cells(i, 2).Value Like "*'*" Or ws.Cells(i, 2).Value Like "*&*" Or ws.Cells(i, 2).Value Like "*-*" Or ws.Cells(i, 2).Value Like "*.*" Then
    ActiveSheet.Hyperlinks.Add Anchor:=ws.Cells(i, 15), Address:="", SubAddress:="'" & ws.Cells(i, 2).Value & "'!A1", TextToDisplay:=ws.Cells(i, 15)
  Else
    ActiveSheet.Hyperlinks.Add Anchor:=ws.Cells(i, 15), Address:="", SubAddress:=ws.Cells(i, 2).Value & "!A1", TextToDisplay:=ws.Cells(i, 15)
  End If
Next i
ws.Activate
End Function

2 个答案:

答案 0 :(得分:0)

不尝试拍摄: 将其更改为:

  ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:=Cells(i, 2).Value & "!A1"

答案 1 :(得分:0)

你走了:

Dim lr As Long, i As Long
Dim sSheet As String
Dim ws As Worksheet

Set ws = ActiveSheet
lr = Cells(Rows.Count, 2).End(xlUp).Row
For i = 2 To lr
    ActiveSheet.Hyperlinks.Add Anchor:=ws.Cells(i, 15), Address:="", SubAddress:=ws.Cells(i, 2).Value & "!A1", TextToDisplay:=ws.Cells(i, 15)
Next i
ws.Activate