简体   繁体   English

使用VBA在Excel中工作表处于保护模式时无法更改单元格值

[英]Unable to change the cell values when work sheet is in protected mode in excel using vba

i am trying to change the particular cell values based on another cell values when the sheet is protected. 我正在尝试在保护工作表时基于另一个单元格值更改特定的单元格值。 code is working fine when the sheet is unprotected. 当工作表不受保护时,代码工作正常。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim na As String, crow As Integer
    Dim subprocesmname As String
    Dim rng1 As Range

    subprocesmname = "Abbvie"
    na = "N/A"
    crow = ActiveCell.Row
    'MsgBox crow
'cell position C3
        If Worksheets(1).Range("C" & crow) = subprocesmname Then
            ActiveSheet.Unprotect ("password")
            Worksheets(1).Range(("H" & crow), ("I" & crow)).Interior.Color = vbYellow
            Worksheets(1).Range(("H" & crow), ("I" & crow)) = na
            Worksheets(1).Range(("H" & crow), ("I" & crow)).Locked = True
            ActiveSheet.Protect ("password")
        Else
            If (Worksheets(1).Range("H" & crow) = na And Worksheets(1).Range("H" & crow) = na) Then
                ActiveSheet.Unprotect ("password")
                Worksheets(1).Range(("H" & crow), ("I" & crow)).Interior.Color = xlNone
                Worksheets(1).Range(("H" & crow), ("I" & crow)).Locked = False
                Worksheets(1).Range(("H" & crow), ("I" & crow)).Delete
                ActiveSheet.Protect ("password")
            End If

        End If
End Sub

Thanks in advance. 提前致谢。

To be able to change some cells by VBA code when sheet is protected you need to set userInterfaceOnly parameter to true in this way: 为了能够在保护工作表时通过VBA代码更改某些单元格,您需要通过以下方式将userInterfaceOnly parameter to true设置userInterfaceOnly parameter to true

ActiveSheet.Protect "password", UserInterfaceOnly:=True

As a result you can change cells from VBA code while user can't change cells manually in excel. 结果,您可以从VBA代码更改单元格,而用户不能在excel中手动更改单元格。

You are using 您正在使用

ActiveSheet.Unprotect ("password")

and then you change cell values at worksheet(1) Is the activesheet when unprotecting the cells worksheet(1)? 然后在工作表(1)上更改单元格值取消保护单元格工作表(1)时,活动表是否有效?

If not then change: 如果没有,请更改:

Worksheets(1).Unprotect "password"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM