Cells属性导致运行时错误'1004'


0

我不断得到应用程序定义或对象定义错误,**中的代码突出显示。我怎样才能解决这个问题?

 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

你错过了这里的背景, Cells不能单独使用。尝试类似的东西ActiveSheet.Cells(...。还有什么价值Row
MátéJuhász

最近有很多这样的问题被问过,我认为这个问题可能与superuser.com/questions/1127224重复。☺
Rajesh S

@RajeshS建议复制目标问题需要至少有一个答案。
Twisty Impersonator

Answers:


0

您收到错误是因为您没有为Row变量定义值。这样做:

Row = value

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

例如,如果您的代码应该影响第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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.