在受保护的 sheet - Excel 上启用宏按钮

Enable Macro button on protected sheet - Excel

我有一个 macro 可以将 rows 从一个 sheet 复制到另一个。但是,我想保护此 sheet 不被编辑。但是,当我这样做时,我无法将 macro 转换为 运行。我试过不同的锁定属性,但它仍然不起作用。

这是我尝试过的:

Option Explicit

Dim pwd As String
Dim ws As Worksheet
pwd = "password"

ws.Unprotect password:=pwd
Next ws

Sub FilterAndCopy()
    Dim rng As Range, sht1 As Worksheet, sht2 As Worksheet

    Set sht1 = Worksheets("SHIFT LOG")
    Set sht2 = Worksheets("CHANGE OF NO'S")

    sht2.UsedRange.ClearContents

    With Intersect(sht1.Columns("B:BP"), sht1.UsedRange)
        .Cells.EntireColumn.Hidden = False
        If .Parent.AutoFilterMode Then .Parent.AutoFilterMode = False

        .AutoFilter Field:=1, Criteria1:="Change of Numbers"

        .Range("A:F, AD:AD, BL:BO").Copy Destination:=sht2.Cells(4, "B")
        .Parent.AutoFilterMode = False

        .Range("F:AD").EntireColumn.Hidden = True
        .Range("AE:BK").EntireColumn.Hidden = True
   End With

    'Go to last cell in column B
    With ActiveSheet
    Range("B5").Select
    Selection.End(xlDown).Select
    End With

End Sub

ws.Protect password:=pwd
Next ws

在你的代码之前和之后尝试这段代码

之前: ' sheet1 和 sheet2 受到保护

Dim pwd As String
Dim ws as WorkSheet
pwd = "password"

For Each ws In Worksheets
    ws.Unprotect Password:=pwd
Next ws

'你的代码

之后:

For Each ws In Worksheets
    ws.protect Password:=pwd
Next ws

希望对您有所帮助

编辑 post 发表评论后

Option Explicit 

Sub FilterAndCopy() 

Dim pwd As String   
Dim sht1, sht2 As Worksheet 
Dim rng As Range    

pwd = "password"    

Set sht1 = Worksheets("SHIFT LOG")  
Set sht2 = Worksheets("CHANGE OF NO'S") 

sht2.Unprotect Password:=pwd 'unprotect the sheet   
sht2.UsedRange.ClearContents ' clear contents   

With Intersect(sht1.Columns("B:BP"), sht1.UsedRange)    

    .Cells.EntireColumn.Hidden = False  
    If .Parent.AutoFilterMode Then .Parent.AutoFilterMode = False   

    .AutoFilter Field:=1, Criteria1:="Change of Numbers"    

    .Range("A:F, AD:AD, BL:BO").Copy Destination:=sht2.Cells(4, "B")    
    .Parent.AutoFilterMode = False  


    .Range("F:AD").EntireColumn.Hidden = True   
    .Range("AE:BK").EntireColumn.Hidden = True  

End With    

'Go to last cell in column B    
With ActiveSheet    

    Range("B5").Select  
    Selection.End(xlDown).Select    

End With    

sht2.Protect Password:=pwd ' protect the sheet  


End Sub