Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel ListRows.Add()在筛选列表时出错_Excel_Listobject_Vba - Fatal编程技术网

Excel ListRows.Add()在筛选列表时出错

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,

我有以下代码(适用于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, 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
请注意两个可能的问题:

  • 在筛选列表中添加新行时,如果新行与筛选条件不匹配,则它可能不可见

  • 如果ListRow的任一侧有任何内容,则新的工作表行可能会将其打断


  • 我认为您的选项与手动尝试的选项基本相同,即插入一个新的工作表行,而不是表格行,或者只是将该行添加到底部。谢谢。在底部添加不是一个选项,但是通过你的另一个提示,我能够找到一个解决方案——我将其作为我自己问题的答案发布。当然,我会在这里(和其他地方)投票支持你。