我有一個帶有洗掉按鈕的代碼,可以根據用戶的選擇相應地洗掉按鈕,但我想避免用戶洗掉特定的行或范圍(相當于行)但是當我嘗試下面的代碼時:
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
我最終收到以下錯誤:
錯誤的數字或引數或...
我仍然是 VBA 的菜鳥,我已經學習了不到一周,并且我一直在開發這個個人專案以學習它,所以非常感謝任何幫助。
ps:如果您需要更多資訊,請告訴我
uj5u.com熱心網友回復:
編輯:拆分邏輯以確定選擇了哪個 listobject 行。
也許是這樣的:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/487671.html
