2

我有以下从 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 上收到此错误:

Run-time error 1004: cannot shift cells in a filtered range or table

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

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

4

1 回答 1

3

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

这是更新的代码:

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 两侧有任何内容,则新的工作表行可能会破坏它。

于 2015-02-09T14:40:59.793 回答