excel - VBA 下标超出范围 - 错误 9

标签 excel vba

有人可以帮我处理这段代码吗?我遇到了下标超出范围错误:

enter image description here

“创建工作表”之后的行在调试器中以黄色突出显示

'Validation of year
 If TextBox_Year.Value = Format(TextBox_Year.Value, "0000") Then

 'Creating Process
'Creation of new sheet
Workbooks.Add
ActiveWorkbook.SaveAs FileName:= _
    "" & Workbooks("Temperature Charts Sheet Creator").Sheets("MENU").Cells(4, 12).Value & "Data Sheet - " & ComboBox_Month.Value & " " & TextBox_Year.Value & ".xls", FileFormat _
    :=xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:= _
    False, CreateBackup:=False

'Creating of the sheets
Windows("Data Sheet - " & ComboBox_Month.Value & " " & TextBox_Year.Value & ".xls").Activate

    Sheets("Sheet3").Select
    Sheets("Sheet3").Name = "31 " & ComboBox_Month.Value
    Sheets("Sheet2").Select
    Sheets("Sheet2").Name = "30 " & ComboBox_Month.Value
    Sheets("Sheet1").Select
    Sheets("Sheet1").Name = "29 " & ComboBox_Month.Value

For i = 28 To 1 Step -1

    Sheets.Add
    ActiveSheet.Name = i & " " & ComboBox_Month.Value

Next

最佳答案

建议进行以下简化:从 Workbooks.Add 捕获返回值而不是下标Windows()之后,如下:

Set wkb = Workbooks.Add
wkb.SaveAs ...

wkb.Activate ' instead of Windows(expression).Activate


一般哲学建议:

避免使用 Excel 的内置函数:ActiveWorkbook、ActiveSheet 和 Selection:捕获返回值,并倾向于使用限定表达式。

仅在最外层宏(子)中使用内置函数一次,并在宏开始时捕获,例如

Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection

在宏期间和宏内不依赖这些内置名称,而是捕获返回值,例如

Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate

此外,尝试使用限定表达式,例如

wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"

Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"

使用限定表达式,例如

newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar" 

这些方法通常会更好地工作,提供更少的困惑结果,在重构时会更加健壮(例如,在方法内和方法之间移动代码行),并且在不同版本的 Excel 中都能更好地工作。例如,在宏执行过程中,从一种 Excel 版本到另一种版本,选择的变化会有所不同。

另请注意,您可能会发现不需要 .Activate使用更多限定表达式时几乎同样如此。 (这可能意味着对于用户来说,屏幕闪烁会更少。)因此整行 Windows(expression).Activate可以简单地被消除,而不是被wkb.Activate取代。 .

(另请注意:我认为您显示的 .Select 语句没有贡献,可以省略。)

(我认为 Excel 的宏记录器在很大程度上促进了这种使用 ActiveSheet、ActiveWorkbook、Selection 和 Select 的更脆弱的编程风格;这种风格留下了很大的改进空间。)

关于excel - VBA 下标超出范围 - 错误 9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12478514/

相关文章:

vba - 在另一个模块中声明一个子/函数可以被其他模块访问,但不能被用户访问

ms-access - 如何修复 "out of stack space"错误?

excel - 选择或复制三个不相邻的单元格 3

vba - 排序组合框 VBA

上个月第一天的Excel公式

excel - 如何使用 vba 在 Excel 中制作蒙版?

excel - 如何在 VBA 中将字符串作为命令运行

excel - 遍历范围的每个循环所需的对象

php - 将自定义列添加到 laravel excel

excel - 查找功能的使用