如何根据另一个单元格的值锁定单元格并执行数据验证

时间:2016-07-01 10:11:21

标签: excel vba excel-vba excel-formula

我对VBA代码很新。现在,我被分配来执行验证Excel工作表中数据的任务。

例如,在我的 A列中,我有一个下拉菜单,使用户只能在“是”或“否”之间进行选择。

  • 如果用户选择“是”,则B列和C列中的单元格将标记为“必填”,不能为空。我想对此进行验证错误。

    **Example 1: If A1 and A30 == YES**
    
    • B1和C1,B30和C30是强制性的

    • 将颜色填充到必填单元格,并在单元格已有值时删除填充颜色

    • 当这些单元格为空且超出时,抛出验证错误 所需的字符数。

      示例2:如果A99 ==否

    • B99将被锁定,不允许用户输入数据 在这个细胞上。我们可以将单元格值添加为“NA”以避免 混乱

我能够使用数据验证和条件格式来捕获它。但是,我无法执行锁定功能,因为根据研究,我需要一个VBA代码。

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效。

将其放入要应用它的工作表的代码模块中。

Private Sub worksheet_change(ByVal target As Range)

    ''''' CHECK IF THE CHANGED CELL IS IN RANGE A1:A99 (OR ANY OTHER RANGE YOU DEFINE)
    If Not Intersect(target, Range("A1:A99")) Is Nothing Then

        ''''' UNPROTECT THE SHEET
        ActiveSheet.Unprotect

        ''''' IF THE CELL CHANGED IS NOW 'YES'
        If target = "Yes" Then

            ''''' WE DEFINE HOW MANY COLUMNS TO MOVE ACROSS FROM THE CELL THAT CHANGED AND DO THE ACTIONS IN THE CODE BELOW
            ''''' SO IN THIS EXAMPLE WE'RE MOVING ACROSS 1 CELL TO B1 AND THEN 2 CELLS TO C1
            ''''' SO TO GET TO AA1 AND AB2 WE'D DO i = 26 to 27
            ''''' IF WE WANTED TO ACCESS AA1 ALL THE WAY THROUGH TO AZ1 WE'D DO i = 26 to 51
            For i = 1 To 2

                ''''' MOVE ACROSS i NUMBER OF CELLS FROM THE CELL THAT CHANGED
                With target.Offset(0, i)

                    ''''' UNLOCK THE CELL
                    .Locked = False

                    '''''SET THE CONDITIONAL FORMATTING
                    .FormatConditions.Add Type:=xlExpression, Formula1:="=ISBLANK(" & target.Offset(0, i).Address & ")"
                    With .FormatConditions(.FormatConditions.Count)
                        .SetFirstPriority
                        .Interior.ColorIndex = 37
                    End With

                End With

            ''''' INCREASE i BY 1 AND LOOP TO AFFECT THE NEXT CELL
            Next i

        ''''' IF THE CELL CHANGED IS NOW 'NO'
        ElseIf target = "No" Then

            ''''' WE DEFINE HOW MANY COLUMNS TO MOVE ACROSS FROM THE CELL THAT CHANGED AND DO THE ACTIONS IN THE CODE BELOW
            For i = 1 To 2

                ''''' MOVE ACROSS i NUMBER OF CELLS FROM THE CELL THAT CHANGED
                With target.Offset(0, i)

                    ''''' SET THE CELL VALUE TO BLANK
                    .Value = ""

                    ''''' LOCK THE CELL
                    .Locked = True

                    ''''' REMOVE THE CONDITIONAL FORMATTING
                    .FormatConditions.Delete

                        ''''' ADD NEW CONDITIONAL FORMATTING HERE IF REQUIRED

                End With

            ''''' INCREASE i BY 1 AND LOOP TO AFFECT THE NEXT CELL
            Next i

        End If

        '''''PROTECT THE SHEET
        ActiveSheet.Protect

    End If

End Sub

请确保在下拉列表所在的A列中将lock设置为false,或者在工作表被锁定时用户将无法更改下拉值。