gpt4 book ai didi

excel - ListRows.Add() 过滤列表时出错

转载 作者:行者123 更新时间:2023-12-04 20:06:36 25 4
gpt4 key购买 nike

我有以下从 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
我理解这个错误,我想我可以解决它,先移除过滤器;但这对用户很粗鲁,迫使他们事后重做过滤器(这可能很复杂)。

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

最佳答案

感谢 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 两侧有任何内容,则新的工作表行可能会破坏它。
  • 关于excel - ListRows.Add() 过滤列表时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28410691/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com