excel - 通过列名确定目标单元格是否在表列中
问题描述
如果目标单元格位于特定列中,我想运行一个过程。
我正在使用列号来确定这一点。如果将额外的列添加到表中,系统就会崩溃。
我的代码如下;
- 列名是“Activity”、“Resources”和“Stakeholders”(在“Schedule”表中);
- 列是 5、7 和 17,在该行
If Target.Column = 5 Or Target.Column = 7 Or Target.Column = 17 Then
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
解决方案
因此,您可以使用表的属性。
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
推荐阅读
- jvm - VisualVM JVM 参数和 GlassFish/Payara JVM 参数之间的区别是正常的吗?
- python - 以 Python 方式更新字符串中的值
- vue.js - Vue 和 Vuex:无法在状态服务中调度操作
- python-3.x - 过滤属于登录用户的数据的最佳方法(Django)
- android - 通过“SDK Manager”安装 Android Emulator 时出错,也无法手动安装
- reactjs - 在 React Native Expo 中打开相机
- apache-flink - flink 1.12.1 示例应用程序在单节点纱线集群上失败
- javascript - 慢慢改变背景颜色
- python - 导入多个具有相似名称的 excel 文件,旋转每个 excel 文件,然后将结果附加到单个文件中
- r - 组合数据帧的行,其中每一行都是 df 本身