簡體   English   中英

Excel VBA-運行時錯誤9(下標超出范圍)

[英]Excel VBA- Run time error 9 (Subscript out of range)

當我嘗試使用以下代碼執行程序時,出現運行時錯誤9。

Private Sub CommandButton1_Click()
    Dim varResponse As Variant

    varResponse = MsgBox("Are you sure want to add this ?", vbYesNo, "Selection")
    If varResponse <> vbYes Then Exit Sub
Dim RowCount As Long
Dim ctl As Control

If Me.TextBox1.Value = "" Then
 MsgBox "Please enter #.", vbOKOnly
 Me.TextBox1.SetFocus
 Exit Sub
 End If
If Me.txtdescription.Value = "" Then
 MsgBox "Please enter a description.", vbOKOnly
 Me.txtdescription.SetFocus
 Exit Sub
 End If
 ' Write data to worksheet
 RowCount = Worksheets("Secretarial Jobs Description").Range("A1").CurrentRegion.Rows.Count
 With Worksheets("Secretarial Jobs Description").Range("A1")
 .Offset(RowCount, 0).Value = Me.TextBox1.Value
 .Offset(RowCount, 1).Value = Me.txtdescription.Value


 End With
 ' Clear the form
For Each ctl In Me.Controls
If TypeName(ctl) = "TextBox" Or TypeName(ctl) = "ComboBox" Then
ctl.Value = ""
ElseIf TypeName(ctl) = "CheckBox" Then
ctl.Value = False
End If
Next ctl

End Sub

因此,調試部分突出顯示了

 RowCount = Worksheets("Secretarial Jobs Description").Range("A1").CurrentRegion.Rows.Count
     With Worksheets("Secretarial Jobs Description").Range("A1") 

是發現錯誤的地方。 我的代碼有誤嗎?

“下標超出范圍”是在按名稱或索引找不到集合中的項目時生成的錯誤。 當前工作簿中極有可能沒有(確切地)命名為“ Secretarial Jobs Description”的工作表。

就像已經說過的,一定是您要調用的工作表名稱不正確或不存在。

您可以嘗試通過對象編號來引用工作表:

RowCount = Sheets(1).Range("A1").CurrentRegion.Rows.count

然后,無論它叫什么位置,都無關緊要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM