我有以下从 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
我理解这个错误,我想我可以解决它,先移除过滤器;但这对用户很粗鲁,迫使他们事后重做过滤器(这可能很复杂)。
有什么可以优雅地解决这个问题?是否有可能以某种方式创建新行但保留(或自动恢复)过滤器?