2014-06-26 221 views
0

我得到運行時錯誤9當我試圖用下面的代碼執行程序。Excel VBA-運行時間錯誤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") 

是在錯誤已經找到。我的代碼有錯誤嗎?

+0

是'現有的祕書職位Description'片。在你目前的工作手冊中?您確定VBA代碼和工作表本身之間沒有拼寫錯誤,補充/缺失白色字符或字母大小寫區別? –

+0

您是否正在運行與數據相同的工作簿或單獨的宏? – tannman357

+0

下面是知春裏Excel對象 Sheet 1中(支付) Sheet2的(客戶端) 表Sheet 3(工作表) Sheet4(用戶) – user3776403

回答

0

「下標超出範圍」是當通過項目的名稱或索引找不到項目時生成的錯誤。很有可能您的當前工​​作簿中沒有(完全)名爲「祕書工作描述」的工作表。

0

就像已經說過的那樣,它必須是您要求的工作表名稱不正確或不存在。

你可以嘗試引用片通過它的對象數:

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

然後,它不會不管它叫什麼,只是什麼地方它是在

+0

我試圖改變,但它仍然無法正常工作 – user3776403

相關問題