使用VBA将表单值插入Excel电子表格

时间:2012-10-28 10:48:47

标签: excel-vba vba excel

我正在尝试使用将表单值插入Excel电子表格,但我当前的代码是将值插入同一行。

  1. 当我的桌子从第3行开始时,我想从那里开始并继续每次自动转移到下一行。行已经设置,我不想插入新行,但会覆盖当前的“空”行。
  2. 当输入202行(可用行的最大数量)时,我希望电子表格返回错误消息对话框。
  3. 我该如何实现这一目标?

    当前代码

        Private Sub btnSubmit_Click()
    
        Dim ws As Worksheet
        Set ws = Worksheets("main")
    
        ' Copy the data to the database
        ws.Rows("4:4").Insert Shift:=xlDown
        ws.Range("A3").Value = cbo_deptCode.Value
        MsgBox ("Booking request has been successfully made")
    
    End Sub
    

2 个答案:

答案 0 :(得分:1)

请尝试此操作,如果您有任何问题或疑虑,请告诉我们:

Sub Button1_Click()
    Dim ws As Worksheet
    Dim i As Long
    Set ws = Worksheets("main")

    ' Copy the data to the database
    i = Cells(Rows.Count, 1).End(xlUp).Row + 1 'Get last empty cell in column A
    If i > 202 Then
        MsgBox "Row 203"
        Exit Sub
    End If

    Range("A" & i).Value = cbo_deptCode.Value
    MsgBox ("Booking request has been successfully made")
End Sub

答案 1 :(得分:1)

类似这样的事情

Private Sub btnSubmit_Click()
    Dim ws As Worksheet
    Dim rng1 As Range
    Set ws = Worksheets("main")
    Set rng1 = ws.Cells(Rows.Count, "a").End(xlUp)
    If rng1.Row > 202 Then
    MsgBox "202 Rows exceeded"  
    Else
    rng1.Offset(1, 0) = cbo_deptCode.Value
    End If
End Sub