即使宏运行正常,仍然出现错误 "Can not do this to a protected sheet"?

Still Getting error "Can not do this to a protected sheet" even though macro is working properly?

所以我以为我已经完成了这段代码并且它正在工作但是当我从 Sheet 1 导航到任何其他 sheet 然后回到 sheet 1 A msgbox弹出并通知我不能对受保护的 sheet 执行此操作。

我不清楚为什么会发生这种情况,因为代码正在执行它应该做的事情...任何帮助将不胜感激。

编辑:我可能应该提到 Sheet 受密码“1”保护。我意识到这不是最合适的密码,它更方便我解决这个问题。

Sub freezesheet()
'set variable for the naming of the new sheet
Dim newname As String

'assignes our open variable to a designated value
Sheets("Sheet1").Activate
newname = Sheets("Sheet1").Range("C2").Value

'copies the sheet to a new sheet after the designated tab
Sheets("Sheet1").Copy after:=Sheets(3)
ActiveSheet.Name = newname

'unprotects the sheet so we can copy and paste as values
ActiveSheet.Unprotect "1"

'makes all of the formulas on the sheets into values and returns you to the original sheet
Cells.Select
    selection.Copy
    selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False

'Re-protects sheet to ensure that we don't make changes to historical data.
ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowFormattingCells:=True, AllowFormattingColumns:=True, _
        AllowFormattingRows:=True

Sheets("Sheet1").Activate

End Sub

下面的重写清理了一些东西。希望在处理好这些问题后,sub 应该 运行 没有错误。即:

  • 检查同名的现有 sheet 以避免潜在的冲突
  • 使用.Value避免将大量数据放入剪贴板
  • 避免在不需要时选择和激活
  • 使用 ThisWorkbook
  • 完全限定范围

详情见评论

Sub freezesheet()
    'set variable for the naming of the new sheet
    Dim newname As String
    'assigns newname variable to a designated value
    newname = ThisWorkbook.Sheets("Sheet1").Range("C2").Value
    ' Check if sheet name already exists
    Dim sh as worksheet
    On Error Resume Next
    Set sh = ThisWorkbook.Sheets(newname)
    On Error GoTo 0
    If Not sh Is Nothing Then
        MsgBox "Error: sheet name already exists, aborted"
        Exit Sub
    End If
    'copies the sheet to a new sheet after sheet 3
    ThisWorkbook.Sheets("Sheet1").Copy after:=Sheets(3)
    With ThisWorkbook.Sheets(4)
        .Name = newname ' New sheet was after sheet 3, so now sheet 4
        'unprotects the sheet so we can copy and paste as values
        .Unprotect "1"
        'makes all of the formulas on the sheets into values
        .UsedRange.Value = .UsedRange.Value
        'Re-protects sheet to ensure that we don't make changes to historical data.
        .Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
                , AllowFormattingCells:=True, AllowFormattingColumns:=True, _
                AllowFormattingRows:=True
    End With
    ThisWorkbook.Sheets("Sheet1").Activate
End Sub