0

On a protected sheet I have a validate list that is dynamicaly updated with VBA code when values in a range are changed. With the worksheet_change event this function is called. First I call RemoveProtect, next MakeValidateList followed by EnableProtect.

Public Sub RemoveProtect()

If ActiveSheet.ProtectContents = True Then
    Application.ScreenUpdating = False
    ActiveWorkbook.Unprotect
    ActiveSheet.Unprotect

    Application.ScreenUpdating = True
End If

End Sub

Public Function makeValidateList(ByVal cell As Range, ByVal r1 As Range) As Integer

Dim arrCargo() As String
Dim i, c As Integer

ReDim arrCargo(1)
arrCargo(0) = "SLOPS"   'vaste waarden
arrCargo(1) = "MT"
c = UBound(arrCargo) + 1

For i = 1 To r1.Count
    If r1.Cells(i, 1).Value <> "" Then
        ReDim Preserve arrCargo(UBound(arrCargo) + 1)
        arrCargo(c) = r1.Cells(i, 1).Value
        c = c + 1
    End If
Next i

With cell.Validation
    .Delete
    .Add Type:=xlValidateList, Formula1:=Join(arrCargo, ",")
    .IgnoreBlank = True
    .InCellDropdown = True
End With

End Function

Public Sub EnableProtect()

        If ActiveSheet.Protect = False Then
            Application.ScreenUpdating = False
            ActiveWorkbook.Protect
            ActiveSheet.Protect UserInterfaceOnly:=True, DrawingObjects:=False

            Application.ScreenUpdating = True
        End If

End Sub

With drawingobjects:=false the sheet remains unprotected, cells are not locked and formulas are not hidden. When drawingobjects:=false is removed the sheet is protected and formulas are hidden. But the validatelist is not updated.

What am I doing wrong?

4

2 回答 2

0

试试下面的代码:

Const strPassWord As String = "1234"

Public Function makeValidateList(ByVal cell As Range, ByVal r1 As Range) As Integer

    Dim arrCargo() As String
    Dim i, c As Integer

    ReDim arrCargo(1)
    arrCargo(0) = "SLOPS"   'vaste waarden
    arrCargo(1) = "MT"
    c = UBound(arrCargo) + 1

    For i = 1 To r1.Count
        If r1.Cells(i, 1).Value <> "" Then
            ReDim Preserve arrCargo(UBound(arrCargo) + 1)
            arrCargo(c) = r1.Cells(i, 1).Value
            c = c + 1
        End If
    Next i

    With cell.Validation
        .Delete
        .Add Type:=xlValidateList, Formula1:=Join(arrCargo, ",")
        .IgnoreBlank = True
        .InCellDropdown = True
    End With

End Function


 Sub EnableProtect()
'Assumed Sheets("Sheet1") change it if needed
    Sheets("sheet1").Range("B1:B100").Locked = False ' You can alter this range as per your requirement
    Sheets("sheet1").Protect Password:=strPassWord, DrawingObjects:=True, Contents:=True, Scenarios:=True
End Sub

 Sub RemoveProtect()
    Sheets("sheet1").Unprotect Password:=strPassWord
End Sub
于 2013-03-30T02:57:02.173 回答
0

使用DrawingObjects:=0而不是DrawingObjects:=false为我工作。

于 2016-11-22T11:50:42.400 回答