变量中的工作表名称包括文件路径

Worksheet Name in Variable Includes Filepath

我将工作表名称存储在一个变量中。当我使用该变量创建一个 hyperlink 时,生成的 link 包含我不想要的文件路径,我只想要工作表名称。非常感谢任何帮助。

Dim wsname as string

wsname = ActiveSheet.Name  ' at this point wsname = "sheetname"

ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=wsname, SubAddress:= _
        "", TextToDisplay:="Tasks" 

Link 创建为 "C:\.....\filename\"sheetname"

我也试过将 wsname 声明为工作表(Dim wsname As Worksheet)。

您可以改用 hyperlink 函数。在公式中添加 # 将创建一个 link 到 sheet 没有文件路径。

Selection.Cells = "=HYPERLINK(""#" & wsname & "!A1"",""Tasks"")"

超链接到另一个工作表(中的一个单元格)

  • 第一个示例在 Selection 的第一个单元格(如果它是一个范围)中创建超链接,链接到同一工作表中的单元格 A1
  • 第二个示例在 Selection 的第一个单元格(如果它是一个范围)中创建超链接,链接到同一工作簿的 Sheet2 中的单元格 A1ActiveWorkbook).
Option Explicit

Sub addHyperlink()
        
    Const dAddress As String = "A1"
        
    If TypeName(Selection) = "Range" Then
        
        Dim sws As Worksheet: Set sws = ActiveSheet
        Dim sCell As Range: Set sCell = Selection.Cells(1)
   
        sws.Hyperlinks.Add _
            Anchor:=sCell, _
            Address:="", _
            SubAddress:="'" & sws.Name & "'!" & dAddress, _
            TextToDisplay:="Tasks"
    
    End If

End Sub

Sub addHyperlink2()
        
    Const dName As String = "Sheet2"
    Const dAddress As String = "A1"
        
    If TypeName(Selection) = "Range" Then
        
        Dim sws As Worksheet: Set sws = ActiveSheet
        Dim sCell As Range: Set sCell = Selection.Cells(1)
        
        On Error Resume Next
        Dim dws As Worksheet: Set dws = sws.Parent.Worksheets(dName)
        On Error GoTo 0
        
        If Not dws Is Nothing Then
            sws.Hyperlinks.Add _
                Anchor:=sCell, _
                Address:="", _
                SubAddress:="'" & dws.Name & "'!" & dAddress, _
                TextToDisplay:="Tasks"
        Else
            MsgBox "The worksheet '" & dName & "' does not exist.", _
                vbCritical, "Add Hyperlink"
        End If
    
    Else
    
        MsgBox "The current selection is not a range.", _
            vbCritical, "Add Hyperlink"
    
    End If

End Sub