创建索引页面Excel宏

时间:2015-03-09 11:31:27

标签: excel-vba vba excel

我正在Excel工作簿中创建索引页面,因为它由许多工作表组成。下面的代码实际应该插入一个从单元格A1开始的新行,并创建一个超链接,将每个工作表链接回索引,但是每次我点击返回索引时都会出现问题"返回索引&#34 ;创建了超链接,我的代码中是否有某种循环?我对VBA有些新意,还没有解决最严重的问题。非常感谢您的任何预期帮助!! :)

Sub Worksheet_Activate()
    Dim wSheet As Worksheet
    Dim l As Long

    l = 1

    With Me
        .Columns(1).ClearContents
        .Cells(1, 1) = "INDEX"
        .Cells(1, 1).Name = "Index"
    End With

    For Each wSheet In Worksheets
        If wSheet.Name <> Me.Name Then
            l = l + 1
            With wSheet
                .Range("A1").Name = "Start_" & wSheet.Index
                .Range("A1").EntireRow.Insert
                .Hyperlinks.Add Anchor:=.Range("A1"), Address:="", _
                SubAddress:="Index", TextToDisplay:="Back to Index"
            End With
            Me.Hyperlinks.Add Anchor:=Me.Cells(l, 1), Address:="", _
        SubAddress:="Start_" & wSheet.Index, TextToDisplay:=wSheet.Name
        End If
    Next wSheet
End Sub

2 个答案:

答案 0 :(得分:0)

这里的问题是,这是在&#34; Worksheet_Activate()&#34;事件。每次激活此工作表(我假设这是Index工作表)时,它都会运行此代码,该代码遍历不是Index工作表的每个工作表,并插入带有超链接的新行。

由于您只需要运行一次,然后将其从Worksheet_Activate()中取出并将其提供给自己的子程序。您可以在需要时调用它,但不是每次都激活Index选项卡。

或者,您可以检查是否已在每个工作表上创建了超链接,如果有,则跳过宏的那一位。类似的东西:

Sub Worksheet_Activate()
    Dim wSheet As Worksheet
    Dim l As Long

    l = 1

    With Me
        .Columns(1).ClearContents
        .Cells(1, 1) = "INDEX"
        .Cells(1, 1).Name = "Index"
    End With

    For Each wSheet In Worksheets
        'Added a check to see if the hyperlink has been created yet already for each sheet
        If wSheet.Name <> Me.Name AND NOT(wSheet.Range("A1").Value = "Back to Index") Then
            l = l + 1
            With wSheet
                .Range("A1").Name = "Start_" & wSheet.Index
                .Range("A1").EntireRow.Insert
                .Hyperlinks.Add Anchor:=.Range("A1"), Address:="", _
                SubAddress:="Index", TextToDisplay:="Back to Index"
            End With
            Me.Hyperlinks.Add Anchor:=Me.Cells(l, 1), Address:="", _
        SubAddress:="Start_" & wSheet.Index, TextToDisplay:=wSheet.Name
        End If
    Next wSheet
End Sub

答案 1 :(得分:0)

试试这个:

Sub Worksheet_Activate()
Dim wSheet As Worksheet
Dim l As Long

l = 1

With Me
    .Columns(1).ClearContents
    .Cells(1, 1) = "INDEX"
    .Cells(1, 1).Name = "Index"
End With

For Each wSheet In Worksheets
    If wSheet.Name <> Me.Name Then
        l = l + 1
        With wSheet
            .Range("A1").Name = "Start_" & wSheet.Index
            .Range("A1").EntireRow.Insert
        End With
        Me.Hyperlinks.Add Anchor:=Me.Cells(l, 1), Address:="", _
    SubAddress:="Start_" & wSheet.Index, TextToDisplay:=wSheet.Name
    End If
Next wSheet
End Sub