如何捕获列表中的新行添加?

我想在Excel 10工作表中执行一个VBA事件处理程序,只要用户在该工作表上添加一个新行到一个列表( Worksheet.ListObjects ()返回实例的列表types),例如通过在最后input数据列表的行(这通过向列表添加新行来扩展列表)。

我怎么做? 除此之外,我想为新行的特定单元格设置默认值。

我目前的想法是处理Worksheet_Change ,并检查Target参数是否在我感兴趣的ListObject.Range范围内。

但是,如何查看用户是否正在使用他/她的单元格更改创build新行,并将其与列表中现有单元格的编辑区分开来?

我可能只是在这里有点愚蠢。 我预计会有一个列表事件,我可以陷阱,但我找不到任何。

我认为你是对的, ListObject没有事件。 使用Worksheet_Change似乎是正确的路要走。 要检测新行vs现有行编辑,您将需要推出自己的方法。

我build议跟踪ListOjects中的行数,以便检测它们何时更改。 为了做到这一点,试着为每个ListOject添加一个隐藏的named range来保存当前的行数。 在打开的文件上填充它们,然后在Worksheet_Change上testing它们。

这将在文件打开时添加或更新隐藏的命名范围(添加到工作簿模块)

 Private Sub Workbook_Open() Dim oList As ListObject Dim sh As Worksheet Dim nm As Name Dim strName As String For Each sh In Me.Worksheets For Each oList In sh.ListObjects 'oList.ListRows.Count strName = oList.Name & "Rows" Set nm = Nothing On Error Resume Next Set nm = Me.Names(strName) On Error GoTo 0 If nm Is Nothing Then Set nm = Me.Names.Add(strName, CStr(oList.ListRows.Count)) Else nm.RefersTo = CStr(oList.ListRows.Count) End If nm.Visible = False Next oList, sh End Sub 

这将检测到什么types的更改。 我已经把它做成了一个WorkBook级别的事件,所以只有一个是需要的所有工作表。 (添加到工作簿模块)

 Private Sub Workbook_SheetChange(ByVal sh As Object, ByVal Target As Range) Dim oList As ListObject Dim nm As Name Dim strName As String For Each oList In sh.ListObjects strName = oList.Name & "Rows" If Not Application.Intersect(Target, oList.DataBodyRange) Is Nothing Then Set nm = Nothing On Error Resume Next Set nm = Me.Names(strName) On Error GoTo 0 If nm Is Nothing Then Set nm = Me.Names.Add(strName, CStr(oList.ListRows.Count)) nm.Visible = False End If If oList.ListRows.Count <> Val(Replace(nm.Value, "=", "")) Then nm.RefersTo = CStr(oList.ListRows.Count) MsgBox "List " & oList.Name & " changed" & vbCrLf & "New Line" Else MsgBox "List " & oList.Name & " changed" & vbCrLf & "Existing Line" End If End If Next End Sub 

注意:这不处理现有ListObject的名称更改的情况。 这是留给读者的一个练习