loop to set variables as worksheet

2019-09-21 17:38发布

Hello my problem is the following: I use to declare for example ws as worksheet and then set it to a specific worksheet. This way when I type the dot after ws I get suggestions for the methods that can be used.

Now I have a workbook with a lot of worksheet and I would like to be able to set each one of them to a different worksheet.

Do you think is it possible to achieve with a loop? thanks

I tried something like EDIT

Dim x as Worksheet 
for i=1 to 50
    x = "ws" & i
    set x = thisworkbook.Sheets(i)
Next

But it does't work Thak you to everyone for your help

2条回答
甜甜的少女心
2楼-- · 2019-09-21 17:51

You can use an array for this:

Dim n
Dim ws() as Worksheet

n = 50

Redim ws(1 to n)

for i = 1 to n
    set ws(i) = thisworkbook.Sheets(i)
Next
查看更多
甜甜的少女心
3楼-- · 2019-09-21 17:59

Or this way:

    Sub AssignWSobjectsToWorksheets()

        Dim i As Integer, n As Integer
        Dim ws() As Worksheet

        n = ThisWorkbook.Worksheets.Count

        ReDim ws(1 To n)

        For i = 1 To n
            Set ws(i) = ThisWorkbook.Worksheets(i)
        Next
    End Sub

Note that Sheets is the collection of all tabs(e.g. including charts), Worksheets just of spreadsheets

查看更多
登录 后发表回答