仍然获取错误“不能做到这一点受保护的工作表”即使macros正常工作?

所以我认为我已经完成了这个代码,它正在工作,但是当我从工作表1导航到其他任何工作表,然后回到工作表1 msgboxpopup并通知我,我不能这样做到受保护的工作表。

我不清楚为什么这是发生,因为代码正在做它应该是…任何帮助,将不胜感激。

编辑:我可能应该提到,工作表是用密码“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 

下面的重写清除了一些东西。 希望照顾好的人,小组应该没有错误地运行。 即:

  • 检查同名的现有表单以避免潜在的冲突
  • 使用.Value避免将大量的数据放入剪贴板
  • 不需要时避免select和激活
  • 完全限定使用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