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