【问题标题】:Excel Listobject table ListRows.count vs range.rows.countExcel Listobject 表 ListRows.count 与 range.rows.count
【发布时间】:2018-09-12 12:56:17
【问题描述】:

我在 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 变量"

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

欢迎任何帮助

非常感谢。

【问题讨论】:

  • RangeListRowsDataBodyRange 是不同的。 ListRowsDataBodyRange 属于 Range 类型,但覆盖范围不同。 DataBodyRange = 包含列表中标题行和插入行之间的数据区域的范围。如果您只有 header 和 insert row ,它会返回 null,因此会出现错误。

标签: excel vba range rows listobject


【解决方案1】:

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


.

.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

【讨论】:

    【解决方案2】:

    如果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
    

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

    希望对您有所帮助!干杯!

    【讨论】:

      猜你喜欢
      • 2016-07-20
      • 2020-01-29
      • 2019-05-14
      • 2019-05-04
      • 2015-03-21
      • 2018-12-31
      • 2021-11-28
      • 2017-07-07
      • 1970-01-01
      相关资源
      最近更新 更多