5
全部,运行时错误'9':下标超出范围 - 仅当Excel VBE关闭时
我在Excel宏中遇到了一些VBA代码的错误。下面是我在尝试的工作流程:
- 我有一个运行代码来创建一个新的工作表,格式模块,并添加一堆值的
- 此相同的模块中,我确定基于单元格区域在最后一行填充(这将始终是不同的,这取决于前面的步骤)
一旦我知道这个范围,我使用下面的代码写入新创建的工作表codemodule,所以我可以设置'change_event'。我只希望当我刚刚确定的范围值改变的change_event触发:`
Dim Startline As Long Startline = 1 Dim x As Integer x = Errors.Count - 1 Dim rng As Range Set rng = Range("D" & LastRow - x & ":" & "D" & LastRow) With ThisWorkbook.VBProject.VBComponents(VRS.CodeName).CodeModule Startline = .CreateEventProc("Change", "Worksheet") + 1 .InsertLines Startline, "Dim rng As Range " Startline = Startline + 1 .InsertLines Startline, "Set rng = Range(" & """" & CStr(rng.Address) & """" & ")" Startline = Startline + 1 .InsertLines Startline, "If Target.Count > 1 Then Exit Sub" Startline = Startline + 1 .InsertLines Startline, "If Intersect(Target, rng) Is Nothing Then Exit Sub" Startline = Startline + 1 .InsertLines Startline, "MsgBox (""Value Changed!..."") " End With
代码工作,并写入以下内容到指定的工作表的codemodule:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Set rng = Range("D58:D62")
If Target.Count > 1 Then Exit Sub
If Intersect(Target, rng) Is Nothing Then Exit Sub
MsgBox ("Value Changed!...")
End Sub`
此代码也可以工作,当范围中的单元格发生更改时,将显示消息框。然而,随着VBE 关闭就会产生错误:
Run-time error '9': Subscript out of range
击中调试带我到行:
With ThisWorkbook.VBProject.VBComponents(WS.CodeName).CodeModule
但它实际上引发错误以下行:
Startline = .CreateEventProc("Change", "Worksheet") + 1
好的,所以我修改了代码,只是从指定的工作表中删除所有代码,并重新写入,而不是每次删除和写入新鲜。这可以防止错误弹出,但会自动打开VBE,而不是....我使用下面的行关闭VBE ...虽然不是很光滑。我打开一个更优雅的解决方案:Application.VBE.MainWindow.Visible = False – gg7aph 2011-05-26 16:58:31
[VBA更改表代码名运行时错误9:下标超出范围]的可能的副本(http://stackoverflow.com/questions/ 41022319/VBA变化的片材代号 - 运行时间错误-9-标出超范围) – ThunderFrame 2016-12-22 23:30:25