Ive a code with a delete button that deletes the button accordingly with the user choise but i want to avoid the user to delete a specific row or Range(equivalent to the line) but when i try the code below:
Private Sub Deletar_Click()
Dim answer As VbMsgBoxResult, tbl As ListObject, error As VbMsgBoxResult
answer = MsgBox("You want to proceed with the delete?", vbYesNo vbQuestion, "Excluir Linha"):
If answer = vbYes & Range.Row(2).Select Then
error = Msgbox("You cant delete this row",vbCritical vbRetryCancel,"Error")
If answer <> vbYes Then Exit Sub
Set tbl = MySheet.ListObjects("DataTable")
tbl.DataBodyRange.Rows(Range.Row - tbl.DataBodyRange.Row).Delete
End Sub
I end up getting the following error:
Wrong number or arguments or...
Im still a noob on VBA,ive been studying for less than a week now, and ive been developing this personal project in order to learn it, so any help would be very appreciate.
ps:If you need extra information please let me know
CodePudding user response:
EDIT: split out the logic for figuring out what listobject row is selected.
Maybe like this:
Sub Deletar_Click()
Dim rw As ListRow
Set rw = SelectedListRow(Selection, mySheet.ListObjects("DataTable"))
If rw Is Nothing Then 'make sure a row in the data table has been selected
MsgBox "First select one or more cells in the data row to be deleted"
ElseIf rw.Index = 1 Then 'first row can't be deleted
MsgBox "The first row cannot be deleted", vbExclamation
Else
'OK to deelte on user confirmation
If MsgBox("Delete selected row?", vbYesNo vbQuestion, "Excluir Linha") = vbYes Then
rw.Delete
End If
End If
End Sub
'Given a Range and a ListObject, return a ListRow corresponding to `rng` (or Nothing
' if rng is noth within the listobject's DatabodyRange
Function SelectedListRow(rng As Range, tbl As ListObject) As ListRow
Dim sel As Range, rowIndex As Long
If Not rng.Parent Is tbl.Parent Then Exit Function 'on different sheets...
Set sel = Application.Intersect(rng.Cells(1), tbl.DataBodyRange) 'only check top-left cell of `rng`
If Not sel Is Nothing Then
rowIndex = 1 (sel.Row - tbl.DataBodyRange.Cells(1).Row) 'which table row is selected?
Set SelectedListRow = tbl.ListRows(rowIndex)
End If
End Function