excel - 过滤列表时 ListRows.Add() 给出错误

标签 excel listobject vba

我有以下从 Worksheet_Change 事件调用的代码(适用于 Excel 2007 及更高版本):

Sub InsertRow(Movs As ListObject, currentRow As ListRow)
    Dim newRow As ListRow

    Set newRow = Movs.ListRows.Add(currentRow.index + 1) 'gives error when list is filtered

    ' below is my custom code, but you don't need to understand it to answer the question:
    Range("xMaxID") = Range("xMaxID") + 1
    newRow.Range.Columns(colID) = Range("xMaxID")
    CopyRow Movs, currentRow, newRow

End Sub

基本上,当用户在 Excel 表格中进行某些更改时,会在当前行下创建一个新行,其中包含数据的副本,并且有几个 ID 字段交叉引用两行,因此我知道它们是相关的.

这工作正常,但是当过滤列表并且事件发生时,我在 ListRows.Add 上收到此错误:

运行时错误 1004:无法移动筛选范围或表格中的单元格

我理解这个错误,我想我可以解决它,首先删除过滤器;但这对用户来说很粗鲁,迫使他们事后重做过滤器(这可能很复杂)。

什么是这个问题的优雅解决方案?是否可以以某种方式创建新行但保留(或自动恢复)过滤器?

最佳答案

感谢 Rory 的提示,一个好的答案是插入整个工作表行,而不仅仅是列表行

这是更新后的代码:

Sub InsertRow(Movs As ListObject, currentRow As ListRow)
    Dim newRow As ListRow

    Movs.Range.Worksheet.Rows(currentRow.Range.Row + 1).Insert
    Set newRow = Movs.ListRows(currentRow.index + 1)

    '(...) rest of sub omitted

End Sub

注意两个可能的问题:

  1. 在过滤列表中添加新行时,如果新行与过滤条件不匹配,可能不可见

  2. 如果 ListRow 两侧有任何内容,新工作表行可能会破坏它。

关于excel - 过滤列表时 ListRows.Add() 给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28410691/

相关文章:

excel - 在某种数据后移动到excel中的单元格

vba - 无法以表格格式获取数据

excel - 如何使用 Excel 公式或 VBA 获取字符串中的十进制(实数)数字?

ms-access - 在 VBA 中 Access 数据项目导入 CSV 文件

Excel IF(OR) - 两个 OR 的公式有效但三个无效?

excel - 在单元格中删除和添加字符

python - 使用 pandas 将 Excel 工作表(Listobject)读取到 python 中

python - 使用 Python 从 Excel 工作表的 ListObject 打开和获取数据

excel - VBA 从列表中删除 Excel 列

vba - Excel - VBA : make Match method less restrictive (by finding a word in a sentence)