在受保护的工作表上,我有一个验证列表,当一个范围内的值发生更改时,该列表会使用VBA代码进行动态更新。使用worksheet_change事件调用此函数。首先我调用RemoveProtect,然后调用MakeValidateList,然后调用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
使用drawingobjects:= false表单保持不受保护,单元格未锁定且公式未隐藏。 当drawingobjects:= false被删除时,工作表受到保护,公式被隐藏。但验证列表未更新。
我做错了什么?
答案 0 :(得分: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
答案 1 :(得分:0)
使用DrawingObjects:=0
代替DrawingObjects:=false
为我工作。