Excel Listobject 表 ListRows.count 与 range.rows.count

Ber*_*nes 1 excel vba rows range listobject

我正在 Excel 中使用列表对象,但遇到以下问题:每次运行代码时,我都会将数据添加到表中。以前我必须删除所有旧数据。

ThisWorkbook.Sheets("comm").ListObjects(1).DataBodyRange.Delete
Run Code Online (Sandbox Code Playgroud)

之后发生的事情是我收到一个错误:

myNrofRowsinCOMM = COMMtbl.DataBodyRange.Rows.Count
Run Code Online (Sandbox Code Playgroud)

我看了这个帖子无济于事。我还是不明白这是怎么回事。

我也尝试了以下操作:

MsgBox "COMMtbl.Range.Rows.Count:" & COMMtbl.Range.Rows.Count
MsgBox "COMMtbl.ListRows.Count:" & COMMtbl.ListRows.Count
MsgBox "COMMtbl.databodyRange.Rows.Count:" & COMMtbl.DataBodyRange.Rows.Count
If COMMtbl.Range.Rows.Count = 1 Then
    COMMtbl.ListRows.Add (1)
End If
Run Code Online (Sandbox Code Playgroud)

如果表是空的(行标题和第一行是空的),第一行给出 2。所以范围有 2 行,这似乎符合现实。COMMtbl.Range.Rows.Count=2 第二个给出 0。我完全不明白。COMMtbl.ListRows.Count=0 第三个给出错误“未设置对象变量或 withblcok 变量”

我正在尝试向表中添加行并用数据填充它们,为此我添加了一行并填充它。我想在最后添加一行,因此我每次都需要计算行数。一切都很好,除了我之前删除了表格的整个内容时的第一个,看起来像:

在此处输入图片说明

欢迎任何帮助

非常感谢。

pau*_*ica 5

我需要复习一下,所以这也可能对你有帮助:

列表对象(表)


.

.Range - Includes the Header, Insert Row and Totals Row (if visible)


.DataBodyRange
  - Contains the data area, between the Header Row and the Insert Row
  - If the ListObject doesn't have a DataBodyRange, this property returns Null


.ListRows
  - Represents all the rows of data (doesn't include Header, Total, or Insert rows)
  - To delete any items from this collection, do not use the Delete method of the item
    Use the Delete method of the range of the item to delete the item
    For example ListRows.Item(1).Range.Delete()
Run Code Online (Sandbox Code Playgroud)

.

当您执行DataBodyRange.Delete该表时,该表不再具有 DataBodyRange 对象,因此要确认表中没有包含数据的行,请替换

myNrofRowsinCOMM = COMMtbl.DataBodyRange.Rows.Count
Run Code Online (Sandbox Code Playgroud)

myNrofRowsinCOMM = COMMtbl.ListRows.Count
Run Code Online (Sandbox Code Playgroud)

来自MSDN 的更多详细信息- ListObject