且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除所选行,但如果选中的行是第一行或最后一行,则不要在Excel VBA(宏)中删除

更新时间:2023-12-04 11:35:28

我将你的代码提高到3行:



 ActiveSheet.Unprotect 
ActiveCell.EntireRow.Delete Shift := xlShiftUp
ActiveSheet.Protect ...





详情请见: Range.Delete Method(Excel) [ ^ ]



注意:您的代码是有潜在危险的,因为它无论在什么情况下都有效!这是什么意思?它从当前活动的工作表中删除行。如果您想删除所需表格中的行,请使用以下内容:

  Dim  wsh 作为工作表
' ...
设置 wsh = ThisWorkbook.Worksheets( Sheet1
wsh.ActiveCell.EntireRow.Delete Shift:= xlShiftUp
' ... 跨度>


how to delete Selected row , but if selected row is First row or last row then dont delete in Excel VBA (Macro)


Sub deleterow()

ActiveSheet.Unprotect

Dim MyRange As Object
    ' Store the selected range in a variable.
    Set MyRange = Selection
    
    
    
    ' Select the entire column.
    Selection.EntireRow.Select
    
      
    ' Insert Columns in all selected sheets.
    Selection.delete
    
    ' Reselect the previously selected cells.
    
    ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= _
        False, AllowFormattingCells:=True, AllowFormattingColumns:=True, _
        AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows _
        :=True, AllowInsertingHyperlinks:=True, AllowDeletingColumns:=True, _
        AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True, _
        AllowUsingPivotTables:=True
    

End Sub

I'll improve your code to 3 lines:

ActiveSheet.Unprotect
ActiveCell.EntireRow.Delete Shift:=xlShiftUp
ActiveSheet.Protect ...



For further information, please see: Range.Delete Method (Excel)[^]

Note: your code is potentially dangerous, because it works no matter of context! What it means? It deletes row from currently active sheet. If you would like to delete row from desired sheet, use something like this:

Dim wsh As Worksheet
'...
Set wsh = ThisWorkbook.Worksheets("Sheet1")
wsh.ActiveCell.EntireRow.Delete Shift:=xlShiftUp
'...