如果目标单元格在特定列中,我想运行一个过程。
我正在使用列号来确定这一点。如果将多余的列添加到表中,系统将崩溃。
我的代码在下面;
If Target.Column = 5 Or Target.Column = 7 Or Target.Column = 17 Then
行的第5、7和17列If Target.Count > 1 Then GoTo exitHandler
On Error Resume Next
Set rngDV = Cells.SpecialCells(xlCellTypeAllValidation)
On Error GoTo exitHandler
If rngDV Is Nothing Then GoTo exitHandler
If Intersect(Target, rngDV) Is Nothing Then
'do nothing
Else
Application.EnableEvents = False
newVal = Target.Value
Application.Undo
oldVal = Target.Value
Target.Value = newVal
If Target.Column = 5 Or Target.Column = 7 Or Target.Column = 17 Then
If oldVal = "" Then
'do nothing
Else
If newVal = "" Then
'do nothing
Else
lUsed = InStr(1, oldVal, newVal)
If lUsed > 0 Then
If Right(oldVal, Len(newVal)) = newVal Then
Target.Value = Left(oldVal, Len(oldVal) - Len(newVal) - 2)
Else
Target.Value = Replace(oldVal, newVal & ", ", "")
End If
Else
Target.Value = oldVal _
& ", " & newVal
End If
End If
End If
End If
End If
exitHandler:
Application.EnableEvents = True
答案 0 :(得分:0)
因此,您可以使用表的属性。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Long
With ActiveSheet.ListObjects("Table1")
c = Target.Column - .ListColumns(1).Range.Column + 1
If Intersect(Target, .DataBodyRange) Is Nothing Then Exit Sub
If .HeaderRowRange(c).Value = "Resources" Or _
.HeaderRowRange(c).Value = "Activity" Or _
.HeaderRowRange(c).Value = "Stakeholders" Then
MsgBox "Yes"
End If
End With
End Sub
答案 1 :(得分:0)
如果有人在工作表中添加列,则可以使用命名范围来避免错误。
例如,列“ 5”是列“ E”。因此,在“ E1”单元格中,您将创建诸如“ ActivityCol”之类的命名范围,并对其他列执行相同的操作(当然使用不同的名称)
然后,您可以在代码中执行
Option Explicit
Sub Test()
Dim ActivityColNo as Long, ResourcesColNo as Long, StakeholdersColNo as Long
......
With Thisworkbook.sheets("Your sheet name")
ActivityColNo = .range("ActivityCol").Column
ResourcesColNo = .range("Some name").Column
StakeholdersColNo = .range("Some other name").Column
End With
........
If Target.Column = ActivityColNo Or Target.Column = ResourcesColNo Or _
Target.Column = StakeholdersColNo Then
.........
End Sub