简体   繁体   English

根据另一个单元格VBA的值锁定/解锁一个单元格

[英]Lock/Unlock One Cell Based on Value of Another Cell VBA

I have done a decent amount of reading about this on this site and a couple others and have not found a solution that works quite yet. 我已经在这个站点和其他几个站点上进行了大量的阅读,但是还没有找到可行的解决方案。

I have a simple calculator built for work in which we need to lock D7 if a Numerical Value other than 0 is entered in D6, unlock if value is zero. 我有一个工作简单的计算器,如果在D6中输入非0的数值,则需要锁定D7,如果值是零则需要解锁。 Then also lock D6 if a Value other than 0 is entered in D7, unlock if value is zero. 然后,如果在D7中输入了非0的值,则也锁定D6;如果该值为零,则解锁。 It's sort of circular...however I do not want someone able to enter a value in one cell if there is a value in the other. 有点循环...但是,我不希望有人能够在一个单元格中输入值,如果另一个单元格中有值。

Also, all the cells in the worksheet are always locked except D4, D5, D6, and D7. 此外,工作表中的所有单元格始终被锁定,但D4,D5,D6和D7除外。 D4 & D5 will always be unlocked. D4和D5将始终被解锁。

Below is my current shot at making this work. 以下是我目前进行这项工作的照片。

CODE

Private Sub Worksheet_Change(ByVal Target As Range)

    If Range("D6").Value <> 0 Then
ActiveSheet.Unprotect ""
        Range("D7").Locked = True
    ElseIf Range("D6").Value = 0 Then
        Range("D7").Locked = False
ActiveSheet.Protect ""
    End If

    If Range("D7").Value <> 0 Then
ActiveSheet.Unprotect ""
        Range("D6").Locked = True
    ElseIf Range("D7").Value = 0 Then
        Range("D6").Locked = False
ActiveSheet.Protect ""
    End If
End Sub

CODE

Problem is I am getting an error on entering 0 in D6 after having a value, and then just getting an error in general when I enter a value in D7 when D6 is 0. 问题是我在拥有值后在D6中输入0时遇到错误,然后通常在D6为0时在D7中输入值时出现错误。

Unable to set the Locked property of the Range class. 无法设置Range类的Locked属性。

Maybe you want this 也许你想要这个

Private Sub Worksheet_Change(ByVal Target As Range)
    ActiveSheet.Unprotect ""
    If Range("D6").Value <> 0 Then
        Range("D7").Locked = True
    ElseIf Range("D6").Value = 0 Then
        Range("D7").Locked = False
    End If

    If Range("D7").Value <> 0 Then
        Range("D6").Locked = True
    ElseIf Range("D7").Value = 0 Then
        Range("D6").Locked = False
    End If
    ActiveSheet.Protect ""
End Sub

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

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