运行时错误“下标超出范围”

时间:2013-07-16 10:42:37

标签: excel vba excel-vba vbscript

我编写了以下脚本,我的运行时错误下标超出了范围。任何人都可以帮我这个吗?(msgbox用作调试器)
提前谢谢。

 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

1 个答案:

答案 0 :(得分:2)

使用

bk.Sheets.Count

在尝试索引到集合之前获取工作表的数字/最后一个索引。