UserForm运行时错误|应用程序定义或对象定义的错误

时间:2019-03-22 08:42:16

标签: excel vba checkbox listbox userform

我用Excel制作了一个用户窗体。它具有TextBoxes和CheckBoxes以及命令按钮。 UserForm以TextBoxes开头,此后出现一些CheckBox,然后继续进行TextBoxes。 cmdAddData_click用于将数据发送到工作表。我搜索了很多东西,但我是这里的新手。

我要发送数据时会给出

  

运行时错误,应用程序定义或对象定义的错误。

感谢所有帮助。

Private Sub cmdAddData_Click()
lastrow = ThisWorkbook.Worksheets("00. Active Customers").Cells(Rows.Count, 1).End(xlUp).Row

ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 0).Value = txtDate.Text
ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 1).Value = txtName.Text

'after 34 textboxes, now for checkboxes

If cbxADSL.Value = True Then
ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 35).Value = "Yes"
Else
ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 35).Value = "No"
End If


If cbxAlarm.Value = True Then
ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 36).Value = "Yes"
Else
ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 36).Value = "No"
End If


'after checkboxes, now for textboxes

ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 122).Value = txtFirstContact.Text
ThisWorkbook.Worksheets("00. Active Customers").Cells(lastrow + 1, 123).Value = txtLastContact.Text


End Sub

1 个答案:

答案 0 :(得分:0)

问题是Cells(lastrow + 1, 0)

Cells的使用类似于Cells(row, column),但列编号以1开头,列0不存在。

此外,您可以使用With StatementIIf function来减少代码:

Private Sub cmdAddData_Click()
    With ThisWorkbook.Worksheets("00. Active Customers")
        lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row

        .Cells(lastrow + 1, 0).Value = txtDate.Text '<-- column number must be fixed
        .Cells(lastrow + 1, 1).Value = txtName.Text

        'after 34 textboxes, now for checkboxes
        .Cells(lastrow + 1, 35).Value = IIf(cbxADSL.Value, "Yes", "No")
        .Cells(lastrow + 1, 36).Value = IIf(cbxAlarm.Value, "Yes", "No")    

        'after checkboxes, now for textboxes
        .Cells(lastrow + 1, 122).Value = txtFirstContact.Text
        .Cells(lastrow + 1, 123).Value = txtLastContact.Text
    End With
End Sub