简体   繁体   中英

run time error “subscript out of range”

I have written the following script and I'm getting runtime error subscript out of range. Can anyone help me with this?(The msgbox is used as a debugger)
Thanks in advance.

 Sub newbook()
     Dim bk As Workbook, sht As Worksheet
     MsgBox ("variables created")

     Set bk = Workbooks.Add
     MsgBox ("book is set")

     With bk
      .Title = "NewBook"
      .SaveAs Filename:="NewBook.xls"
     End With

    MsgBox ("Book is created")

    Set sht = bk.Sheets.Add
    MsgBox ("sheet is set")

    bk.Sheets(1).Name = "Hello 1"
    bk.Sheets(2).Name = "Hello 2"
    bk.Sheets(3).Name = "Hello 3"
    bk.Sheets(4).Name = "Hello 4"

    MsgBox ("everything is completed")

 End Sub

Use

bk.Sheets.Count

to get the number/last index of sheets, before you try to index into the collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM