簡體   English   中英

VBA 取消保護工作表,運行 sub,然后重新保護工作表?

[英]VBA un-protect sheet, run sub, then re-protect sheet?

這是我的問題,當我在解鎖工作表的情況下測試它們時,我有 subs 工作,但是當我鎖定工作表以保護某些單元格不被選擇或刪除/更改時,subs 錯誤。 所以我需要在我的 sub 中添加一個解鎖的部分,運行主代碼,然后重新鎖定工作表。

我正在尋找這樣的東西

Sub Example ()
Dim sample as range
set sample as range("A3:Z100")
Application.ScreenUpdating = false
UN-PROTECT CODE
'Existing sub code here
RE-PROTECT CODE
Application.ScreenUpdating = True
End Sub

然而,我不知道實現這一目標的代碼應該是什么樣子。 我嘗試過研究,但我發現的只是基於評論的不完整代碼,並沒有一直工作。 我確實找到了一個建議,可以在出錯時讓錯誤處理程序重新保護工作表,但也不知道如何編寫。 有什么建議?

哦,將使用此工作表的人將無法訪問工作表密碼。 我計划讓模塊有自己的密碼保護,並將子程序附加到按鈕上。 因此,如果需要,將 Sheet 解鎖密碼放在 sub 中就可以了。

發表我的原始評論作為答案。

如果您使用宏記錄器,然后保護和取消保護工作表,它將顯示代碼。

編輯:添加以下內容。

如果您嘗試取消保護不受保護的工作表,則會出現錯誤。 我使用此函數來測試工作表是否受保護,將結果存儲在Boolean變量中,然后測試該變量以查看a)在寫入之前是否必須保護工作表,以及b)在以下位置檢查工作表是否應受到保護:程序結束。

Public Function SheetIsProtected(sheetToCheck As Worksheet) As Boolean
    SheetIsProtected = sheetToCheck.ProtectContents
End Function

您需要它來刪除密碼嗎? 這對我有用

Sub macroProtect1()

Sheet1.Unprotect Password:="abc" 

'Enable error-handling routine for any run-time error
On Error GoTo ErrHandler   

'this code will run irrespective of an error or Error Handler
Sheet1.Cells(1, 1) = UCase("hello")

'this code will give a run-time error, because of division by zero. The worksheet will remain unprotected in the absence of an Error Handler. 
Sheet1.Cells(2, 1) = 5 / 0

'this code will not run, because on encountering the above error, you go directly to the Error Handler 
Sheet1.Cells(3, 1) = Application.Max(24, 112, 66, 4)

Sheet1.Protect Password:="abc" 

ErrHandler:
  Sheet1.Protect Password:="abc" 

End Sub 

有一個類似的問題,並在網絡上找到以下代碼:SubprotectAll()Dim myCount Dim i myCount = Application.Sheets.Count Sheets(1).Select i = 1 To myCount ActiveSheet.Protect“ password”,true,true如果i = myCount然后如果ActiveSheet.Next.End選擇結束,則結束End

Sub Unprotect1()
    Dim myCount
    Dim i
    myCount = Application.Sheets.Count
    Sheets(1).Select
        For i = 1 To myCount
            ActiveSheet.Unprotect "password"
            If i = myCount Then
            End
        End If
        ActiveSheet.Next.Select
    Next i
End Sub

請注意,它旨在保護/取消保護工作簿中的所有工作表,並且工作正常。 對原作者表示歉意和尊重,我不記得在哪里找到它(但我不主張它)...

受保護的最常見對象是工作表對象。通過鎖定包含公式的單元格,可以保留公式。

Sub Demo()
    Dim sh As Worksheet
    Set sh = ActiveSheet

    sh.Unprotect
        '   DO YOUR THING
    sh.Protect
End Sub

這是我針對不需要密碼的情況(這是我遇到的大多數情況)的非常簡單的技術:

Dim IsProtected As Boolean

IsProtected = SomeWkSh.ProtectContents: If IsProtected Then SomeWkSh.Unprotect

'Do stuff on unprotected sheet...

If IsProtected Then SomeWkSh.Protect

當然,您可以通過使用With SomeWkSh語句稍微簡化語法,但如果“Do stuff...”部分指的是更大的、跨越With語句對象的方法的屬性,那么這樣做會破壞該功能。

另請注意, Protect方法的Contents參數默認為True ,因此您不必顯式指定它,但為了清楚起見,您可以這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM