仍然得到错误“无法对受保护的工作表执行此操作”,即使宏工作正常吗?

时间:2017-05-10 13:45:51

标签: excel vba excel-vba excel-2013

所以我认为我已经完成了这段代码并且它正常工作但是当我从Sheet 1导航到任何其他工作表然后再返回到工作表1时弹出一个msgbox并通知我我不能这样做受保护的表。

我不清楚为什么会发生这种情况,因为代码正在完全按照预期进行...任何帮助都将受到赞赏。

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

@RestController
public class IslandController {

    @Autowired
    private IslandRepository islandRepo;

    @Autowired
    private PagedResourcesAssembler pagedResourcesAssembler;

    @Autowired
    private PersistentEntityResourceAssembler resourceAssembler;

    @RequestMapping(method = GET, value = "islands")
    public ResponseEntity<?> getAllIslands(Pageable page) {
        Page<Island> islandList = islandRepo.findAll(page);
        return new ResponseEntity<>(pagedResourcesAssembler.toResource(islandList, resourceAssembler), HttpStatus.OK);
    }

1 个答案:

答案 0 :(得分:1)

以下重写可以清理一些事情。希望对那些照顾的人来说,sub应该没有错误地运行。即:

  • 检查具有相同名称的现有工作表以避免潜在的冲突
  • 使用.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