【问题标题】:Create a hyperlink to a sheet with same name as the value in the selected cell in Excel through VBA通过 VBA 创建指向与 Excel 中所选单元格中的值同名的工作表的超链接
【发布时间】:2023-02-05 21:29:22
【问题描述】:

我试图让代码首先检查我所在的工作表中是否选择了单个单元格,然后检查工作簿中是否存在一个工作表,其值与所选单元格中的值相同。

如果满足这些条件,我将尝试在选定的单元格中创建一个超链接,该超链接指向具有相同名称/值的工作表。

例如,如果我选择其中包含值“1000”的单元格 (A1),并且有一个名为“1000”的工作表,我希望代码在单元格 A1 中创建一个指向名为“1000”的工作表的超链接。

我尝试了以下代码,它给了我“运行时错误'5':这行代码中的过程调用或参数无效;

selectedCell.Hyperlinks.Add Anchor:=selectedCell, Address:="", SubAddress:=selectedCell.Value & "!", TextToDisplay:=selectedCell.Value

Sub CreateHyperlinkToSheet()
    Dim selectedCell As Range
    Set selectedCell = Selection

    If selectedCell.Count <> 1 Then
        MsgBox "Please select a single cell.", vbExclamation
        Exit Sub
    End If

    If Not SheetExists(selectedCell.Value) Then
        MsgBox "No sheet exists with the name '" & selectedCell.Value & "'.", vbExclamation
        Exit Sub
    End If

    selectedCell.Hyperlinks.Add Anchor:=selectedCell, Address:="", SubAddress:=selectedCell.Value & "!", TextToDisplay:=selectedCell.Value
End Sub

Function SheetExists(sheetName As String) As Boolean
    On Error Resume Next
    SheetExists = (Len(Sheets(sheetName).Name) > 0)
    On Error GoTo 0
End Function


【问题讨论】:

  • selectedCell.Hyperlinks.Add Anchor:=selectedCell, Address:="", SubAddress:="'" &amp; selectedCell.Value &amp; "'!A1", TextToDisplay:=selectedCell.Value
  • 尝试用您的代码替换,不幸的是得到了相同的错误消息。
  • 我编辑了我的评论(因为我在最后省略了 .Value 中的最后一个“e”)——目前的语法是有效的语法
  • 仍然收到相同的错误消息,调试器将我指向这行代码。
  • 好的,这是因为您的标签名称是一个数字...

标签: excel vba


【解决方案1】:

我通过用这行代码替换给出错误消息的代码行来修复它;

selectedCell.Formula = "=HYPERLINK(""#'" & sheetName & "'!A1"", " & sheetName & ")"

如果值和工作表名称是数字,则此方法有效。 如果它是一个字符串,则应该将“”添加到公式中的第二个参数。

然而,它不是最干净的解决方案,因为它向选定的单元格添加了一个公式,而不是保持单元格值不变。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多