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

标签 excel vba range rows listobject

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

ThisWorkbook.Sheets("comm").ListObjects(1).DataBodyRange.Delete

之后发生的事情是我收到一个错误:
myNrofRowsinCOMM = COMMtbl.DataBodyRange.Rows.Count

我看过 this post无济于事。我仍然不明白发生了什么。

我也尝试了以下方法:
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

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

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

enter image description here

欢迎任何帮助

非常感谢。

最佳答案

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

ListObject (Table)

.

.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()

.

当你这样做 DataBodyRange.Delete该表不再具有 DataBodyRange 对象,因此要确认表中没有包含数据的行,请替换
myNrofRowsinCOMM = COMMtbl.DataBodyRange.Rows.Count


myNrofRowsinCOMM = COMMtbl.ListRows.Count

更多详情来自 MSDN - ListObject

关于Excel Listobject 表 ListRows.count 与 range.rows.count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49625994/

相关文章:

excel - VBA向上/向下 move 选定范围(有偏移?)

excel - 避免 Excel 中的循环引用

regex - 使用正则表达式将编号列表数组拆分为多行编号列表

c++ - 当我调用工作簿的 PrintPreview() 方法时出现 Com 错误 800a03ec

vba - excel vba复制到空白单元格

excel - 在 Excel VBA 中获取工作表区域的大小

vba - 从自定义集合类中的对象引发事件

Java 和 MongoDB 查询日期范围

ruby-on-rails - 使用 Rails 和 Roo-xls gem 在保存之前验证上传的 Excel 文件

regex - 第 n 次出现正则表达式的 sed 打印行