2017-06-09 136 views
1

我有一個受保護的Excel表格,帶有命令按鈕可以刪除行。 用戶可以突出顯示並選擇多行,並通過單擊命令按鈕將其刪除。但我不希望第一行(第11行)被刪除,因爲它包含公式和格式。我有下面的代碼在命令按鈕中刪除。它工作正常,並保護第11行,當用戶突出顯示並選擇第11行到第40行(因爲這裏的活動行是11)。但問題出在用戶突出顯示錶單中按鈕的行並單擊命令按鈕時,它甚至會刪除第11行,因爲此處的活動行超過了11(示例活動行= 40)。請詳細說明如何保護第11行,防止用戶刪除,即使他們選擇刪除。保護第一行免受刪除

Private Sub CommandButton2_Click() 
If ActiveCell.Row > 11 Then 
ActiveSheet.Unprotect "xxx" 
Selection.EntireRow.Delete 
ActiveSheet.Protect "xxx", True, True 
End If 
End Sub 
+0

刪除行後,您可以使用'.Range(「A1」)。Formula'方法重新編寫這些公式。只需在上面的代碼中的'end sub'之前對公式進行硬編碼 – Maddy

+0

@Maddy Nikam - 我使用了下面的語法。我沒有完全理解你的語法。你可以請解釋一下或者一個例子會很棒......非常感謝... –

回答

1

這是一種方法。檢查用戶是否已選擇第11行

Private Sub CommandButton2_Click() 
    Dim rng As Range 
    Dim rw As Variant 

    '~~> Check if what the user selected is a valid range 
    If TypeName(Selection) <> "Range" Then 
     MsgBox "Select a range first." 
     Exit Sub 
    End If 

    Set rng = Selection 

    '~~> Check if the user has selected Row 11 
    For Each rw In rng.Rows 
     If rw.Row = 11 Then 
      MsgBox "Please do not select Row 11" 
      Exit Sub 
     End If 
    Next rw 

    ActiveSheet.Unprotect "xxx" 
    rng.Rows.Delete 
    ActiveSheet.Protect "xxx", True, True 
End Sub 
+0

太棒了!你的語法超棒!感謝您的幫助。 –

+0

很高興能有幫助:) –