Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

vba - Sort array size

I am trying to create a hyperlink of various worksheets on a table of contents using visual basic.

The first sheet is the table of contents. The worksheets to be included in the table of contents therefore start at worksheet2. I am unablet to change the array to begin at worksheet 2.

These are my lines of code

'Create Table of Contents

 ' Create array with locations

    Set firstsheet = Worksheet(2).Value

    '  Dim arrworksheets(2 To Worksheets.Count) As Long

    For x = arr(firstsheet) To UBound(myArray)

    Set sht = Worksheets(myArray(x))

    sht.Activate

    With Content_sht

      .Hyperlinks.Add .Cells(x + 2, 3), "", _

      SubAddress:="'" & sht.Name & "'!A1", _

      TextToDisplay:=sht.Name

      .Cells(x + 2, 2).Value = x

    End With

  Next x

Thank you so much in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As far as I can tell you are wanting to iterate through all the sheets in your workbook, but excluding the first sheet in the list - the contents page.

There's a great example of how to achieve this here, which judging by the similarity in your code, you may have already had a peek at.

The relevant part you want to look at is:

'Create Array list with sheet names (excluding Contents)
  ReDim myArray(1 To Worksheets.Count - 1)

  For Each sht In ActiveWorkbook.Worksheets
    If sht.Name <> ContentName Then
      myArray(x + 1) = sht.Name
      x = x + 1
    End If
  Next sht

Here, instead of trying to exclude the contents page based on it's order in the workbook, it excludes it based on the sheet name - If sht.Name <> ContentName.

However for completeness, if you still want to do this based on the position that each sheet is in, you can simply use a For loop instead of an array and begin at 2 (remember, sheet collections are not 0-base indexed):

Dim x As Integer
Dim count As Integer
Dim Content_sht As Worksheet
Dim sht_nam As String

count = ActiveWorkbook.Worksheets.count
Set Content_sht = Worksheets("Sheet1") 'whatever your contents page is called


For x = 2 To count

    sht_nam = Worksheets(x).Name

    With Content_sht
      .Hyperlinks.Add .Cells(x + 2, 3), "", _
      SubAddress:="'" & sht_nam & "'!A1", _
      TextToDisplay:=sht_nam
      .Cells(x + 2, 2).Value = x
    End With

Next x

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...