我正在使用 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 变量”
我正在尝试向表中添加行并用数据填充它们,为此我添加一行并填充它。我想在最后添加一行,因此我每次都需要计算行数。一切都很好,除了我之前删除表格的全部内容时的第一个,看起来像:
欢迎任何帮助
非常感谢。
最佳答案
.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/