将表格中的数据提交到电子表格表格中

时间:2013-11-24 11:52:21

标签: excel vba excel-vba

我是VBA的新手,我正在尝试将数据从vba表单中提取到我的电子表格表中。 我收到错误:运行时错误1004,应用程序定义或对象定义错误。 标记为错误的代码行是:.Offset(RowCount, 0).Value = Me.FirstnameBox.Value

这是我的代码:

Private Sub SubmitNewUser_Click()

Dim RowCount As Long
Dim ctl As Control

    ' Check user input
    If Me.FirstnameBox.Value = "" Then
        MsgBox "Please enter the users firstname.", vbExclamation, "Add New User"
        Me.FirstnameBox.SetFocus
    Exit Sub
    End If

    If Me.SurnameBox.Value = "" Then
        MsgBox "Please enter the users surname.", vbExclamation, "Add New User"
        Me.SurnameBox.SetFocus
    Exit Sub
    End If

    If Me.AccessBox.Value = "" Then
        MsgBox "Please enter the user number.", vbExclamation, "Add New User"
        Me.AccessBox.SetFocus
    Exit Sub
    End If

    If Not IsNumeric(Me.AccessBox.Value) Then
        MsgBox "The user number must only contain a number.", vbExclamation, "Add New User"
        Me.AccessBox.SetFocus
    Exit Sub
    End If

    If Me.SecBox.Value = "" Then
        MsgBox "Please enter the users security number.", vbExclamation, "Add New User"
        Me.SecBox.SetFocus
    Exit Sub
    End If

    Dim iRow As Long
    Dim ws As Worksheet
    Set ws = Worksheets("Sheet2")

    'find  first empty row in database
    iRow = ws.Cells(Rows.Count, 1) _
    .End(xlUp).Offset(1, 0).Row

    If WorksheetFunction.CountIf(ws.Range("D1", ws.Cells(iRow, 1)), Me.AccessBox.Value) > 0 Then
        MsgBox "Duplicate Code Found", vbCritical
        Exit Sub
    End If

        ' Write data to worksheet
        RowCount = Worksheets("Sheet2").Range("A1").CurrentRegion.Rows.Count
        With Worksheets("Sheet2").Range("A1")
            .Offset(RowCount, 0).Value = Me.FirstnameBox.Value
            .Offset(RowCount, 1).Value = Me.MiddlenameBox.Value
            .Offset(RowCount, 2).Value = Me.SurnameBox.Value
            .Offset(RowCount, 3).Value = Me.AccessBox.Value
            .Offset(RowCount, 4).Value = Me.SecBox.Value
        End With

        End Sub

1 个答案:

答案 0 :(得分:0)

尝试将RowCount = Worksheets("Sheet2").Range("A1").CurrentRegion.Rows.Count更改为

RowCount = Worksheets("Sheet2").Cells(Worksheets("Sheet2").Rows.Count,1).End(XlUp).Row

如果RowCount设置为65536,那么尝试从单元格A1偏移将是A65537并将导致错误(假设您使用的是Excel 2003),因为65536是最大行数。