首页 > 解决方案 > 创建一个新工作表并在摘要工作表中超链接该工作表

问题描述

我开发了一个代码来复制工作表并使用插入框中给出的值重命名工作表名称,然后在摘要表中复制相同的值并选择最后一个单元格并粘贴值,但我想创建超链接以便如果我单击该值,它将带我到该表。

我被困在给出正确的子地址上。

Private Sub CommandButton1_Click()
    Dim sName As String
    Dim oRng As Range

    sName = InputBox("New Shipment", "New AWB Number", "Enter the AWB Number")

    If sName <> "" Then
        ThisWorkbook.Sheets("Templete").Copy Before:=Sheets(3)  
        ActiveSheet.Name = sName
        MsgBox "New AWB Number Tracking Added"
    Else
        MsgBox "Failed"  
    End If

    Sheets("Summary").Select
    Range("B" & Rows.Count).End(xlUp).Offset(1, 0).Activate

    ActiveCell.Value = sName
    'ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _
        "'Sheet(3)'!A1"
End Sub

当我运行它时,我收到一个错误:

“参考无效”

请帮忙。

标签: excelvba

解决方案


使用时您总是会遇到问题SelectActivate但我怀疑您的主要问题是您的超链接子地址。您尝试将其设置为'Sheet(3)'!A1"Excel 无法识别的位置,因为它是工作表位置(VBA 识别)而不是工作表名称。看看下面

Private Sub CommandButton1_Click()
    Dim sName As String
    Dim oRng As Range
    Dim nWs As Worksheet

    sName = InputBox("New Shipment", "New AWB Number", "Enter the AWB Number")

    If sName <> "" Then
        With ThisWorkbook
            .Sheets("Templete").Copy Before:=.Sheets(3)
            Set nWs = .Sheets(3)
        End With
        nWs.Name = sName

        With Sheets("Summary")
            With .Range("B" & Rows.Count).End(xlUp).Offset(1, 0)
                .Value2 = sName
                .Parent.Hyperlinks.Add Anchor:=.Cells, Address:="", SubAddress:= _
                                        "'" & nWs.Name & "'!A1"
            End With
        End With

        MsgBox "New AWB Number Tracking Added"
    Else
        MsgBox "Failed"
    End If
End Sub

您可能还应该为此添加一个检查,以针对现有工作表测试用户输入的重复或无效名称。


推荐阅读