excelvbauser-controlsuserformcommandbutton

Lock cells after userform input


I need that after a userform is submited that row and cells are locked.

When you insert data in userform those data go to tab called "table". I need tab TABLE to be locked and to allow only userform input.

I need rows and cells from A4 to AF4 onwards to be locked for editing.

I tried with this code.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim MyRange As Range

Set MyRange = Intersect(Range("A1:D100"), Target)
If Not MyRange Is Nothing Then
    Sheets("Sheet1").Unprotect password:="hello"
    MyRange.Locked = True
    Sheets("Sheet1").Protect password:="hello"
End If
End Sub

This is how my command button looks

Private Sub CommandButton2_Click()
Dim sh As Worksheet, lastRow As Long
Set sh = Sheets("Details")lastRow = sh.Range("A" & Rows.Count).End(xlUp).row + 1
sh.Range("A" & lastRow).value = TextBox3.value
sh.Range("B" & lastRow).value = TextBox4.Text
sh.Range("C" & lastRow).value = TextBox5.Text
Unload Me
End sub

Solution

  • First, manually lock the cells from A4:AF[ChooseTheLastRow] and then protect the worksheet with a password and do not allow the selecting of locked cells.

    Then in your code do this.

    Private Sub CommandButton2_Click()
    
      Dim sh As Worksheet
      Set sh = Sheets("Details") 'you called this TABLE in your text above, no?
    
      With sh
    
          .unprotect "PASSWORD"
    
          Dim lastRow As Long
          lastRow = .Range("A" & Rows.Count).End(xlUp).row + 1
    
          .Range("A" & lastRow).value = TextBox3.value
          .Range("B" & lastRow).value = TextBox4.Text
          .Range("C" & lastRow).value = TextBox5.Text
    
          .protect "PASSWORD"
    
      End With
    
    End sub