Cells 属性导致运行时错误“1004”

Cells 属性导致运行时错误“1004”

我一直得到应用程序定义或对象定义错误,** 中的代码被突出显示。我该如何修复此问题?

 Private Sub Update_Click()
  answer = MsgBox("Are you sure you want to update the Staff Record?", 
  vbYesNo + vbQuestion, "Update Staff Record")
  If answer = vbYes Then
    *Cells(Row, 1) = TextBox6.Text*
    Cells(Row, 2) = TextBox1.Text
    Cells(Row, 3) = TextBox2.Text
    Cells(Row, 4) = TextBox3.Text
    Cells(Row, 5) = ComboBox1.Text
    Cells(Row, 6) = ComboBox2.Text
    Cells(Row, 7) = TextBox4.Text
    Cells(Row, 8) = ComboBox3.Text
    Cells(Row, 9) = TextBox5.Text
 End If
End Sub

答案1

您收到错误是因为您尚未为Row变量定义值。请按如下方式操作:

Row = value

其中value是一个整数,指定您希望所有 Cells 语句对其操作的工作表行。

例如,如果您的代码应该影响第 2 行,那么您的代码将如下所示:

Private Sub Update_Click()
  Row = 2
  answer = MsgBox("Are you sure you want to update the Staff Record?", 
  vbYesNo + vbQuestion, "Update Staff Record")
  If answer = vbYes Then
    Cells(Row, 1) = TextBox6.Text
    Cells(Row, 2) = TextBox1.Text
    Cells(Row, 3) = TextBox2.Text
    Cells(Row, 4) = TextBox3.Text
    Cells(Row, 5) = ComboBox1.Text
    Cells(Row, 6) = ComboBox2.Text
    Cells(Row, 7) = TextBox4.Text
    Cells(Row, 8) = ComboBox3.Text
    Cells(Row, 9) = TextBox5.Text
 End If
End Sub

此外,这里有一种更简洁的方法,使用 MsgBox 函数根据用户的响应执行代码:

If MsgBox("Are you sure you want to update the Staff Record?", _
  vbYesNo + vbQuestion, "Update Staff Record") = vbYes Then
    *run this if user clicks Yes*
End If

这种方法不会将用户的响应存储在变量中,然后单独测试它。相反,它会在一行代码中执行相同的操作。(但是,如果您稍后需要在代码中再次使用用户的响应,那么将其存储在变量中将是更好的选择。)

相关内容