数据input到一个单元格后locking特定的单元格组

一旦数据input到一个单元格中,我需要使用VBA代码来locking一组特定的单元格。 上下文:用户将沿着一行input用户名,传递等。行中的一些单元格被locking,一些单元格被解锁,以便他们需要input数据的地方,但是一旦他们在最后一个单元格中回答他们的数据,我想要该行中的所有先前未locking的单元格将被locking。

如果没有经常更新和locking单元格,我很难解决这个问题。 这就是我现在所拥有的。

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) ActiveCell.Select If Range("O22") <> "" Then ActiveSheet.Unprotect Range("F22,G22,J22,K22,L22,O22").Select Selection.Locked = True ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True End If End Sub 

如果您希望工作簿自动locking范围,如果“O22”不为空,那么这是您需要的代码

 Private Sub Worksheet_Change(ByVal Target As Range) 'Check if O22 has changed before running rest of code If Not Intersect(Target, Range("O22")) Is Nothing Then 'If the final column isn't empty then If Range("O22") <> vbNullString Then 'Unprotect the sheet Me.Unprotect 'Lock the target cells Me.Range("F22,G22,J22,K22,L22,O22").Locked = False 'Reprotect the sheet Me.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True End If End If End Sub 

一般来说,在VBA中,您应该避免使用“select”或“激活”,而是引用对象,请参阅此问题。

很难准确地判断工作簿的结构,但是如果您将此代码复制到“工作表”代码模块中,那么它应该适用于工作表中的问题,如果您需要在更多工作簿级别上工作,请给予更多需要什么的细节。

听起来像你想要更像这样的东西(注意它也是在不同的事件)

 Private Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 20 Then Range("F22,G22,J22,K22,L22,O22").Locked = True ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True End If End Sub 

20更改为希望代码在其更改上运行的任何列。