从表单提交数据到电子表格表格

我是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 

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

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

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