首页 文章

循环遍历范围中的单元格并根据其值锁定单元格

提问于
浏览
0

好吧,我说我有一系列来自A1:B10的细胞 . A1到A10范围内的单元格包含一个带有2个选项的下拉列表(lock,dont_lock) . B1到B10范围内的单元格是空单元格,允许用户输入数据 . 我想要做的是根据相邻单元格中的值锁定单个单元格 . 因此,如果单元格A1设置为“锁定”,则我锁定单元格B1 . IF单元A2设置为“dont_lock”,则B2未锁定,依此类推 . 我尝试使用下面的代码中显示的for循环,但它不起作用 . 有人可以帮忙吗?

Dim rCell As Range
Dim rRng As Range

Set rRng = Sheet1.Range("A1:B10")

For Each rCell In rRng.Cells
    If rCell = "Lock" Then
    Range("B1").Locked = True

End If

Next rCell

2 回答

  • 4

    在Excel中,默认情况下会锁定单元格 . 如果要解锁单元格,则必须实际指定该行为 . 但是,它目前没有受到保护 . 因此,如果您想要锁定行为,请务必调用 Sheet1.Protect .

    现在,如果我正确理解你的解释,你会用这样的东西做得更好:

    Dim rCell As Range
    Dim rRng As Range
    
    Set rRng = Sheet1.Range("A1:A10") 'Exclude B as you are only checking A.
    Sheet1.Unprotect
    For Each rCell In rRng.Cells
        'Avoid if else structure since locking depends on result of evaluation only.
        rcell.Offset(0,1).locked = rcell.Value = "Lock"
    Next rCell
    Sheet1.Protect
    
  • 1

    请尝试以下代码 . 只有您的代码问题是缺少rCell.value =“Lock” . 您只锁定所有单元格的Cell B1,而不是锁定相邻的所有单元格:)

    这是一个示例代码

    Option Explicit
    
    Sub lockNextCell()
    Dim wkSheet As Worksheet
    Dim rng As Range, rCell As Range
    
    Set wkSheet = Sheets("Sheets1") '-- use your own sheet
    Set rng = wkSheet.Range("A3:A12") '-- use your own range
    
    For Each rCell In rng
        If rCell.Offset(0, 0).Value = "Lock" Then
            rCell.Offset(0, 1).Locked = True '-- here we are locking the adjacent cell
        else
            rCell.Offset(0, 1).Locked = False
        End If
    Next rCell
    
    End Sub
    

    丹尼尔谈到保护纸张时只是注意事项:

    这是reference from MSDN:"If you lock a cell and protect the worksheet, then you cannot type data into the cell, modify the data currently in the cell, or change other attributes of the cell (such as cell formatting)"

相关问题