Excel ListRows.Add()在筛选列表时出错
我有以下代码(适用于Excel 2007和更新版本)是从工作表\u更改事件调用的:Excel ListRows.Add()在筛选列表时出错,excel,listobject,vba,Excel,Listobject,Vba,我有以下代码(适用于Excel 2007和更新版本)是从工作表\u更改事件调用的: 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,
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上遇到此错误。在筛选列表并发生事件时添加:
运行时错误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
请注意两个可能的问题:
我认为您的选项与手动尝试的选项基本相同,即插入一个新的工作表行,而不是表格行,或者只是将该行添加到底部。谢谢。在底部添加不是一个选项,但是通过你的另一个提示,我能够找到一个解决方案——我将其作为我自己问题的答案发布。当然,我会在这里(和其他地方)投票支持你。