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

时间:2018-04-03 08:57:45

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

欢迎任何帮助

非常感谢。

2 个答案:

答案 0 :(得分:3)

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

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

的更多详情

答案 1 :(得分:1)

如果您没有ListObject .DataBodyRange Is Nothing中的数据,那么您就无法计算行数。您可以使用n = ListObject.Range.Rows.Count然后ListObject.ListRows(n).Range

获取ListObject的最后一行

我不知道你手边的数据是怎么样的,但是为了这个例子,如果你只有一列和一行,你可以将数据添加到最后一行而不用担心如果表是空的,然后使用示例中的.Add方法。

Dim current_n_rows As Integer

With ThisWorkbook.Sheets("comm").ListObjects(1)
    .DataBodyRange.Delete
    current_n_rows = .ListRows.Count
    .ListRows(current_n_rows).Range.Value = NewData
    .ListRows.Add
End With

您可以围绕填充表格所需的循环包装此语句。

希望它有所帮助!干杯!