Excel 2013 Workbook_BeforeSave在Excel 2016中生成错误

时间:2018-08-30 15:39:53

标签: excel vba excel-2016

此宏在Excel 2013中有效,但是现在我已更新到2016,它不再起作用。旨在将单元格中的单元格锁定在工作簿中的多个工作表中。

Private Sub Workbook_BeforeSave()

    'Resume to next line if any error occurs
    On Error Resume Next

    Dim WS_Count As Integer
    Dim I As Integer
    Dim Cell As Range

    'Set WS_Count equal to the number of worksheets in the active workbook.
    WS_Count = ActiveWorkbook.Worksheets.Count

    'loop through all of the Worksheets
    For I = 1 To WS_Count
        With ActiveWorkbook.Worksheets(I)
             'first of all unprotect the entire sheet and unlock all cells
            .Unprotect Password:="open"
            .Cells.Locked = False
             'Now search for non blank cells and lock them
             'unlock blank cells
            For Each Cell In ActiveWorkbook.Worksheets(I).UsedRange
                If Cell.Value > "" Then
                    Cell.Locked = True
                Else
                    Cell.Locked = False
                End If
            Next Cell
             'Now protect the entire sheet
            .Protect Password:="open"
        End With
    Next I

    Exit Sub
End Sub

删除On Error Resume Next后,它在Cell.Locked = True上出错。

2 个答案:

答案 0 :(得分:1)

在Excel 2016中,workbook_BeforeSave方法需要其他非可选参数

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

即使您的代码忽略了它们,也需要将它们包括在方法的声明中。

答案 1 :(得分:1)

我解决了Noob Mistake的问题,我在模块中而不是工作簿中有宏。