【问题标题】:Are there ListObject events in VBA?VBA 中有 ListObject 事件吗?
【发布时间】:2019-09-29 08:07:56
【问题描述】:
【问题讨论】:
标签:
.net
excel
vba
vsto
listobject
【解决方案1】:
没有直接的Events,但有解决方法。
例如。您可以检查用户是否尝试点击ListObject下的一行或一行
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim tbl As ListObject: Set tbl = ListObjects("Table1")
If Not Intersect(Target, tbl.Range.Offset(1, 0)) Then
Exit Sub 'clicked elsewhere, exit
Else
'tried to access table do something <code here>
End If
End Sub
【解决方案2】:
我不知道 Listobjects 的任何特定事件,但您可以使用工作表的事件轻松重现该行为。
如果您希望在单击一个单元格时触发事件:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim mytbl As ListObject
Set tbl = thisworkbook.sheets("whatever sheet").ListObjects("Table1")
dim overlap as range
set overlap = Intersect(Target, mytbl.databodyrange)
If Not overlap in nothing Then
'your selection is totally or partially inside the table
if overlap.count=1
' you selected only one cell
' do something
' If you want to access the cell selected
' use target.range
Else
msg box('you did not make a proper selection of one cell inside the listobject')
End If
End if
End Sub
如果您希望在更改列表对象单元格的值时触发事件:
您一次只能更改一个单元格。所以没有必要检查细胞的数量。它总是一个。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim mytbl As ListObject
Set tbl = thisworkbook.sheets("whateversheet").ListObjects("Table1")
' the list object table is in sheet 'whateversheet"
dim overlap as range
set overlap = Intersect(Target, mytbl.databodyrange)
If Not overlap is nothing Then
' your selection is inside the table
' code is here when you change the value of a cell of the table.
' do some stuff
' if you want to add the introduced value:
newvalue=target.value
Else
' You might inform the user that the change took place outside the listobject
End If
End Sub
您还可以编写其他事件。双击等。
基本上,它总是关于查找事件是否由属于列表对象的工作表的单元格触发(因此是范围的交集)。如果是则触发相应的代码。