【问题标题】:Are there ListObject events in VBA?VBA 中有 ListObject 事件吗?
【发布时间】:2019-09-29 08:07:56
【问题描述】:

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

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

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

【问题讨论】:

    标签: .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
      

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

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

      【讨论】:

        猜你喜欢
        • 2018-12-31
        • 2019-05-14
        • 2019-05-04
        • 1970-01-01
        • 1970-01-01
        • 2019-03-31
        • 2019-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多