Hyperlink code shows Subscript out of range error vba excel

拈花ヽ惹草 提交于 2019-12-25 05:48:12

问题


I have a hyperlink vba code that activates a hidden worksheet when clicked. But for some reason every time I run I get an error saying

"Subscript out of Range"

at the line of code Worksheets(MySheet).Visible = xlSheetVisible

The code is

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)

Linkto = Target.SubAddress
Name = InStr(1, Linkto, "!")
If Name > 0 Then
    MySheet = Left(Linkto, Name - 1)
    Worksheets(MySheet).Visible = xlSheetVisible
    Worksheets(MySheet).Select
    MyAddr = Mid(Linkto, Name + 1)

    Worksheets(MySheet).Range(MyAddr).Select
 End If
End Sub

回答1:


You should avoid using variable names such as "Name" which could be reserved words. In this particular case, I guess Name will refer to the current worksheet (The one on which the Hyperlink is set)

Try the same code by replacing the variable "Name" by, for example "myName"

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)

  Linkto = Target.SubAddress
  myName = InStr(1, Linkto, "!")
  If myName > 0 Then

      MySheet = Left(Linkto, myName - 1)
      Worksheets(MySheet).Visible = xlSheetVisible
      Worksheets(MySheet).Select
      MyAddr = Mid(Linkto, myName + 1)
      Worksheets(MySheet).Range(MyAddr).Select

  End If
end sub

and also, as an advice,

  • Use "OPTION EXPLICIT" at the beginning of your VBA to force you explicit declaration of variables
  • use variable names in line with the content. You call the variable "Name" but you actually store in it the position of the exclamation mark in the hyperlink target... kind of confusing...

Hope that fixes your issue...



来源:https://stackoverflow.com/questions/32052927/hyperlink-code-shows-subscript-out-of-range-error-vba-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!