我需要帮助。我正在使用一个包含超过200行和25列的Excel文档。下面的代码尝试锁定和解锁行F3和列G,H,I和J3中的数据。有没有办法清理代码并让代码对所有行F3:F200执行此过程?我试图避免必须为每一行执行代码(例如,F4和代码的其余部分,然后是F5等)。任何人的想法?
非常感谢提前。
Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Unprotect Password:="code"
If Range("F3") = "Yes" Then
Range("G3").Locked = False
Range("H3").Locked = False
Range("I3").Locked = False
Range("J3").Locked = False
ElseIf Range("F3") = "No" Then
Range("G3").Locked = True
Range("H3").Locked = True
Range("I3").Locked = True
Range("J3").Locked = True
End If
ActiveSheet.Protect Password:="code"
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
End Sub
答案 0 :(得分:1)
这样的事情:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Range, v
ActiveSheet.Unprotect Password:="code"
For Each c in Range("F3:F200")
v = c.Value
If v = "Yes" or v = "No" then
c.Offset(0,1).Resize(1,4).Locked = (v = "No")
End If
Next c
ActiveSheet.Protect Password:="code"
End Sub
答案 1 :(得分:1)
这是一个快速重写,循环所有范围...我唯一的问题是,是否每行都有一个是/否来表示锁定/解锁?
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long
ActiveSheet.Unprotect
For i = 1 To 200
If Cells(i + 2, 6) = "yes" Then
Range(Cells(i + 2, 7), Cells(i + 2, 10)).Locked = False
ElseIf Cells(i + 2, 6) = "no" Then
Range(Cells(i + 2, 7), Cells(i + 2, 10)).Locked = True
End If
Next i
ActiveSheet.Protect
End Sub