gpt4 book ai didi

excel - 使用 VBA 数组函数对过滤数据进行数据损坏

转载 作者:行者123 更新时间:2023-12-03 20:45:14 27 4
gpt4 key购买 nike

做一个非常简单的电子表格
enter image description here
在其上运行以下代码。它只是将工作表复制到一个数组然后再返回。它不应该对工作表产生任何影响。

Option Explicit

Sub Test()
Dim vArr As Variant

' Copy the contents of the sheet to a 2D variant array
vArr = Sheets("Sheet1").Cells(1, 1).CurrentRegion

' Copy the variant array back to the sheet
Sheets("Sheet1").Cells(1, 1).Resize(UBound(vArr, 1), UBound(vArr, 2)) = vArr

' There should be no difference to the sheet
End Sub
一切正常。现在过滤工作表并排除第 2 行(或实际上任何其他行)
enter image description here
再次运行代码,你会得到一团糟:
enter image description here
这是一个错误还是这里有一些更深层次的哲学在起作用?有没有办法解决这个问题,除了清除过滤器。
更新
我还要注意隐藏行和过滤行之间存在差异。如果您隐藏一行,则代码可以正常工作。它似乎只与过滤有关。

最佳答案

如果您将 VBA 脚本更改为使用 for 循环,则可以解决此问题。
稍微修改你的 VBA 脚本我没有看到你上面提到的问题。

Option Explicit

Sub Test()
Dim vArr As Variant

' Copy the contents of the sheet to a 2D variant array
vArr = Sheets("Sheet1").Cells(1, 1).CurrentRegion


' Copy the variant array back to the sheet
'Sheets("Sheet1").Cells(1, 1).Resize(UBound(vArr, 1), UBound(vArr, 2)) = vArr

Dim row As Integer
Dim col As Integer

For row = 1 To UBound(vArr, 1)

For col = 1 To UBound(vArr, 2)
'Debug.Print vArr(row, col)
Sheets("Sheet1").Cells(row, col) = vArr(row, col)
Next col
Next row
' There should be no difference to the sheet
End Sub

关于excel - 使用 VBA 数组函数对过滤数据进行数据损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65969051/

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