ListRows.Add() 在过滤列表时给出错误
ListRows.Add() gives error when list is filtered
我有以下从 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 table 中进行某些更改时,会在当前行下创建一个新行,其中包含数据的副本,并有几个 ID 字段交叉- 引用两行,所以我知道它们是相关的。
这工作正常,但是当过滤列表并发生事件时,我在 ListRows.Add 上收到此错误:
Run-time error 1004: cannot shift cells in a filtered range or table
我明白这个错误,我想我可以解决这个问题,先删除过滤器;但这对用户很粗鲁,迫使他们之后重做过滤器(这可能很复杂)。
有什么优雅解决这个问题的方法?是否有可能以某种方式创建新行但保留(或自动恢复)过滤器?
感谢 Rory 的提示,一个好的答案是 插入整个 sheet 行,而不仅仅是一个 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
注意两个可能的问题:
在筛选列表中添加新行时,如果不符合筛选条件,您的新行可能不可见。
如果您的 ListRow 两边都有任何东西,新的 sheet 行可能会破坏它。
我有以下从 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 table 中进行某些更改时,会在当前行下创建一个新行,其中包含数据的副本,并有几个 ID 字段交叉- 引用两行,所以我知道它们是相关的。
这工作正常,但是当过滤列表并发生事件时,我在 ListRows.Add 上收到此错误:
Run-time error 1004: cannot shift cells in a filtered range or table
我明白这个错误,我想我可以解决这个问题,先删除过滤器;但这对用户很粗鲁,迫使他们之后重做过滤器(这可能很复杂)。
有什么优雅解决这个问题的方法?是否有可能以某种方式创建新行但保留(或自动恢复)过滤器?
感谢 Rory 的提示,一个好的答案是 插入整个 sheet 行,而不仅仅是一个 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
注意两个可能的问题:
在筛选列表中添加新行时,如果不符合筛选条件,您的新行可能不可见。
如果您的 ListRow 两边都有任何东西,新的 sheet 行可能会破坏它。