我是VBA的新手,如果通过“数据验证”从列表中选择某个文本,我会尝试锁定单元格。 我一直收到错误“运行时错误'424':需要对象。 我在这段代码上收到错误; 如果Application.Intersect(目标,范围(“B7,b1000”))是什么,那么, 我在这做错了什么
Sub Locking2()
'
' Locking2 Macro
'Private Sub Worksheet_Change(ByVal Target As Range)
Const csPASSWORD As String = "tndppp"
'--
If Application.Intersect(Target, Range("B7,b1000")) Is Nothing Then
Exit Sub ' Do Nothing
End If
'--
''' 'B7:B1000' has been changed '''
' Unprotect sheet
ActiveSheet.Unprotect_
ActiveSheet.Unprotect Password:=csPASSWORD
With Range("b8:b1000")
If UCase(Range("B7,b1000").Value) = "PP" Then
' Lock 'E7:N1000'
.Locked = True
Else
' Unlock 'E7:N1000'
.Locked = False
End If
End With
'--
'Protect sheet
ActiveSheet.Protect _
Password:=csPASSWORD, _
DrawingObjects:=True, _
Contents:=True, _
Scenarios:=True
End Sub
答案 0 :(得分:0)
您尚未在Target
函数中定义Locking2
。你可以这样做:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Target, Range("B7:b1000")) Is Nothing Then
Call Locking2(Target)
End If
End Sub
Sub Locking2(ByVal Target As Range)
Const csPASSWORD As String = "tndppp"
' Unprotect sheet
ActiveSheet.Unprotect Password:=csPASSWORD
ActiveSheet.Cells.Locked = False
With Range("E7:N1000")
allPP = True
For Each r In Range("B7:b1000")
If UCase(r.Value) <> "PP" Then
allPP = False
Exit For
End If
Next
If allPP Then
' Lock 'E7:N1000'
.Locked = True
Else
' Unlock 'E7:N1000'
.Locked = False
End If
End With
'Protect sheet
ActiveSheet.Protect _
Password:=csPASSWORD, _
DrawingObjects:=True, _
Contents:=True, _
Scenarios:=True
End Sub
此更改应修复错误