简体   繁体   English

Excel VBA-运行时错误9(下标超出范围)

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

i getting run time error 9 when i trying to execute the program with the following code. 当我尝试使用以下代码执行程序时,出现运行时错误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

Whereby the debug part highlighted that 因此,调试部分突出显示了

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

is where the error had found. 是发现错误的地方。 Am i having mistake on the code? 我的代码有误吗?

"Subscript out of range" is the error generated when an item is not found into a collection by its name or its index. “下标超出范围”是在按名称或索引找不到集合中的项目时生成的错误。 It's highly likely that there is no worksheet in your current workbook that is (exactly) named "Secretarial Jobs Description". 当前工作簿中极有可能没有(确切地)命名为“ Secretarial Jobs Description”的工作表。

Like has been said, it must be that the sheet name you're calling for is incorrect or doesn't exist. 就像已经说过的,一定是您要调用的工作表名称不正确或不存在。

You could try referencing the sheet by it's object number: 您可以尝试通过对象编号来引用工作表:

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

Then it won't matter what it's called, just what place it is in. 然后,无论它叫什么位置,都无关紧要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM