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

UserForm Run-time-error | Application-defined or object defined error

我用 Excel 创建了一个用户窗体。它有 TextBoxes 和 CheckBoxes 以及命令按钮。 UserForm 以 TextBoxes 开始,然后出现一些 CheckBoxes,TextBoxes 继续。 cmdAddData_click 用于发送数据到 sheet。我搜索了很多,但我是这里的新手。

当我想发送数据时,它给出

run-time error, Application-defined or object defined error.

感谢所有帮助。

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

问题是Cells(lastrow + 1, 0)

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

此外,您可以使用 With Statement and the IIf 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