Use a for loop to add new sheets in workbook

2019-07-10 04:22发布

I am trying to write a For...Next loop to create a set number of Worksheets in a Workbook. The the number of worksheets is set by the user from a dashboard, at an earlier point.

Can somebody point me in the right direction? This is my code, so far:

For i = 1 To siteCount
    'I know the below won't work, and I also tried site_ & i, but no luck
    Set site_i = Sheets.Add(after:=Sheets(Worksheets.Count))
    site_i.Name = "Sheet Name"
Next i

1条回答
在下西门庆
2楼-- · 2019-07-10 04:39

With some small adjustments, your code will basically work:

Option Explicit

Sub AddSheets()

    Dim siteCount As Integer
    Dim i As Integer
    Dim site_i As Worksheet

    siteCount = 4

    For i = 1 To siteCount
        Set site_i = Sheets.Add(after:=Sheets(Worksheets.Count))
        site_i.Name = "Sheet_Name_" & CStr(i)
    Next i

End Sub
查看更多
登录 后发表回答