1

I'm trying to insert form values into my Excel spreadsheet using but my current code is inserting values into the same row.

  1. As my table starts from row 3, I want to start from there and continue by automatically shifting to the next row each time. The rows are already set and I don't want to insert new rows but overwrite the current 'empty' rows.
  2. When 202 rows (maximum no. of rows available) have been entered then I want the spreadsheet to return an error message dialog.

How can I go about achieving this?

Current Code

    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 Answers 2

1

something like this

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
Sign up to request clarification or add additional context in comments.

Comments

1

Please try this and let us know if you have any questions or concerns:

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

3 Comments

Thanks it works really well. But I'm having the problem where it always skips row 3 for some reason. Even though it is the current first empty row on the table, it skips it and starts at row 4. Any idea how I can fix this?
@methuselah The code above doesn't actually use ws. It works on the ActiveSheet.
Sry, I was away... But I see you got your answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.