+ Reply to Thread
Results 1 to 2 of 2

Code help needed.

  1. #1
    Registered User
    Join Date
    03-01-2005
    Posts
    11

    Code help needed.

    Hi.
    Thanks to all who have helped me so far.

    This is hopefully the last step!

    I have now got a macro that looks at a worksheet in one workbook (source.xls), and uses the data to write a list in a different workbook (dailystaff.xls). What I need is to run the macro in a For/Next loop writing lists on a series of different worksheets (all in dailystaff.xls). The macro currently contains the line:

    Set mySht2 = Workbooks("DailyStaff.xls").Worksheets("Day1")

    which defines where the list is to be written. DailyStaff.xls actually contains 28 worksheets, and I would like to be able to have the worsheet name change automatically to Day2, Day3 etc. The alternative would be to write out the whole macro 28 times, which would be cumbersome and plain ugly.

    For x = 1 to 28
    Set mySht x+1 = Workbooks("DailyStaff.xls").Worksheets("Day x")
    [rest of macro here]
    Next x

    This would obviously not work as it is, but what I need is the correct syntax for having a variable as part of a filename.

    Thanks
    David.

  2. #2
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,258
    Hello David,

    You were so close to solving this yourself. The Workbook and Worksheets are Collection objects. All collections can be referenced one of two ways. You can reference an item by Index it's index value or by it's key. The key is a String.

    So your code can written Using Keys:

    Dim mySht as Worksheet
    For x = 1 to 28
    Set mySht = Workbooks("DailyStaff.xls").Worksheets("Day" & Str(X))
    [rest of macro here]
    Next x


    Or This Way with Index Values:

    Dim mySht As Worksheet
    For x = 1 to 28
    Set mySht = Workbooks("DailyStaff.xls").Worksheets(X)
    [rest of macro here]
    Next x


    Sincerely,
    Leith Ross

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1