2013-11-24 87 views
1

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

錯誤時RowCount的值是什麼?你可以在檢查錯誤之前添加「msgbox RowCount」。 – Sam

+1

我編輯過你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

+0

Hi Sam,65536是顯示的值。 約翰 - 道歉。 – Brunette

回答

0

嘗試改變RowCount = Worksheets("Sheet2").Range("A1").CurrentRegion.Rows.Count

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

如果行數設置爲65536,然後試圖抵消從單元格A1將是A65537並將導致錯誤(假設您正在使用Excel 2003),因爲65536是最大行數。

+0

山姆,這工作得很好..我改變了「行+ 1」爲「行+ 0」,以便所有行都用作您在每個條目之間留下一行的示例。 :-) 謝謝! – Brunette

+0

@布魯內特沒問題。很高興我能幫上忙。 – Sam