VBA中有ListObject事件吗?

时间:2019-05-11 20:42:33

标签: .net excel vba vsto listobject

我从.NET API(VSTO)中看到ListObject确实存在此对象的事件。 VSTO Docs

但是,我没有在.NET中进行编码,我只是在做普通的Excel VBA,并想利用ListObject引发的事件。

The official Microsoft Documentation on ListOjbect没有显示任何事件,但我希望也许可以通过一种“非正式”的方式来实现?

2 个答案:

答案 0 :(得分:0)

没有直接的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

答案 1 :(得分:0)

我不知道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

您还可以编程其他事件。双击等。

基本上,它总是与查找是否由属于列表对象的工作表的单元格触发事件有关(因此范围是相交的)。如果是,则触发相应的代码。