使用excel创建名称和超链接到该名称的动态范围

时间:2013-08-13 21:03:12

标签: excel-vba hyperlink range vba excel

我正在尝试开发一种快速简便的项目管理跟踪器。我目前正在使用输入框来获取要添加的项目名称(PrjName)。然后代码将复制模板并将其粘贴到下一个可用COLUMN的“Projects”工作表中(项目之间的额外空间为+1)。然后,我想将PrjName添加为仪表板工作表上的项目列表,但将其添加为超链接,该超链接将链接到项目已粘贴到“项目”工作表上的相应列。我已经想出了如何复制/粘贴我想要的样子,但我不知道如何开始创建超链接的引用。我想我可以通过使用项目名称来创建一个命名范围,以某种方式引用粘贴的信息,然后引用该超链接的名称,但我不知道如何实现这一点。这是我迄今为止所拥有的,但距离正确还有很长的路要走。

Private Sub CommandButton1_Click()
Dim FirstBlankCol As Range

PrjName = InputBox("Enter the name of the project", "User Input Required")
If PrjName = "" Then Exit Sub

'Find First Blank Cell to add new Project on Summary Worksheet
Set FirstBlankCol = Range("B" & Rows.Count).End(xlUp).Offset(1, 0)
Worksheets("Summary").Hyperlinks.Add Anchor:=FirstBlankCol, Address:="", SubAddress:= _
"PrjName", TextToDisplay:=PrjName

With Sheets("Projects")
    Select Case Sheets("Projects").Range("A1") = ""
        Case True 'paste in Col A if A1 is empty
            Sheets("Template").Range("A1:F5").Copy
            Sheets("Projects").Range("A1") _
            .PasteSpecial Paste:=xlPasteColumnWidths
            Sheets("Projects").Range("A1") _
            .PasteSpecial Paste:=xlPasteAllUsingSourceTheme
        Case False 'paste in next col
            Sheets("Template").Range("A1:F5").Copy
            Sheets("Projects").Range("IV1").End(xlToLeft).Offset(0, 6) _
            .PasteSpecial Paste:=xlPasteColumnWidths
            Sheets("Projects").Range("IV1").End(xlToLeft).Offset(0, 6) _
            .PasteSpecial Paste:=xlPasteAllUsingSourceTheme
        End Select
        Application.CutCopyMode = False
End With

End Sub

1 个答案:

答案 0 :(得分:0)

尝试一下:

Private Sub CommandButton1_Click()

    Dim ws As Worksheet
    Dim wsPrj As Worksheet
    Dim wsTmp As Worksheet
    Dim rngDest As Range
    Dim strProjectName As String

    strProjectName = InputBox("Enter the name of the project", "User Input Required")
    If Len(Trim(strProjectName)) = 0 Then Exit Sub  'Pressed cancel

    Set ws = ActiveSheet
    Set wsPrj = Sheets("Projects")
    Set wsTmp = Sheets("Template")

    Application.ScreenUpdating = False
    If Len(wsPrj.Range("A1").Text) = 0 Then Set rngDest = wsPrj.Range("A1") Else Set rngDest = wsPrj.Cells(1, Columns.Count).End(xlToLeft).Offset(, 6)
    wsTmp.Range("A1:F5").Copy
    rngDest.PasteSpecial xlPasteAllUsingSourceTheme
    rngDest.PasteSpecial xlPasteColumnWidths
    Application.CutCopyMode = False

    ActiveWorkbook.Names.Add Replace(strProjectName, " ", "_"), "='" & wsPrj.Name & "'!" & rngDest.Address
    ws.Hyperlinks.Add ws.Cells(Rows.Count, "B").End(xlUp).Offset(1), "", Replace(strProjectName, " ", "_"), , strProjectName
    Application.ScreenUpdating = True

End Sub