Search code examples
excelvbauserform

Is it possible to disable adding of empty row in spreadsheet using a Userform in Excel?


Hello so I have a code here that allows me to add/insert a new row in the spreadsheet using a userform, however it also allows me to add BLANK/EMPTY rows. Does anyone know how to disable that? I have no knowledge in coding so I base on tutorials but I couldn't seem to find one.

Here is the code:

Private Sub cmbAdd_Click()
    Dim sheet As Worksheet
    Set sheet = ThisWorkbook.Sheets("TRY TRY")

    nextrow = sheet.Cells(Rows.Count, 1).End(xlUp).Row + 1

    sheet.Cells(nextrow, 1) = Me.cmbSchema
    sheet.Cells(nextrow, 2) = Me.cmbEnvironment
    sheet.Cells(nextrow, 3) = Me.cmbHost
    sheet.Cells(nextrow, 4) = Me.cmbIP
    sheet.Cells(nextrow, 5) = Me.cmbAccessible
    sheet.Cells(nextrow, 6) = Me.cmbLast
    sheet.Cells(nextrow, 7) = Me.cmbConfirmation
    sheet.Cells(nextrow, 8) = Me.cmbProjects

    MsgBox "Data Added!"

End Sub

Can I have a MsgBox again saying "You cannot add empty rows." ?


Solution

  • Try following, change sheet name in case of your sheet.

    Private Sub CommandButton1_Click()
        Dim sht As Worksheet
        Set sht = ThisWorkbook.Sheets("TRY_TRY")
    
        nextrow = sht.Cells(Rows.Count, 1).End(xlUp).Row + 1
    
        If Me.cmbSchema = "" Or _
            Me.cmbEnvironment = "" Or _
            Me.cmbHost = "" Or _
            Me.cmbIP = "" Or _
            Me.cmbAccessible = "" Or _
            Me.cmbLast = "" Or _
            Me.cmbConfirmation = "" Or _
            Me.cmbProjects = "" Then
    
            MsgBox "Empty value is not allowed", vbCritical, "Data Missing"
    
        Else
    
            sht.Cells(nextrow, 1) = Me.cmbSchema
            sht.Cells(nextrow, 2) = Me.cmbEnvironment
            sht.Cells(nextrow, 3) = Me.cmbHost
            sht.Cells(nextrow, 4) = Me.cmbIP
            sht.Cells(nextrow, 5) = Me.cmbAccessible
            sht.Cells(nextrow, 6) = Me.cmbLast
            sht.Cells(nextrow, 7) = Me.cmbConfirmation
            sht.Cells(nextrow, 8) = Me.cmbProjects
    
            MsgBox "Data Added!"
    
        End If
    End Sub