【问题标题】:Excel VBA, Writing from array to list object, including cells hidden by filters [duplicate]Excel VBA,从数组写入列表对象,包括被过滤器隐藏的单元格[重复]
【发布时间】:2016-12-27 03:48:49
【问题描述】:

我在 Excel 2013 中工作,在 VBA 中编写一个宏,我正在尝试为列表对象(表)的列中的所有单元格分配一个值,包括一些可能被过滤器。为每个单元格单独分配一个值似乎大大减慢了这个过程,我发现一个建议将范围复制到一个变体数组中,遍历数组以更改值,然后将数组复制回范围。

varray = table.DataBodyRange.Columns(columnIndex).Value
For i = 1 to UBound(varray, 1)
    If (condition) then
        varray(i, 1) = i
    End If
Next i
table.DataBodyRange.Columns(columnIndex).Value = varray

在大多数情况下,这可以解决速度问题。当表中的任何列上有过滤器时,它就会停止工作。据我所知,数组仍会从表中正确复制,但不会正确复制回来。过滤器隐藏的第一个单元格之前的所有单元格都会被正确处理,但隐藏的单元格不会改变,隐藏单元格之后的所有单元格都将设置为数组中的第一个值。

这仅在单元格被过滤器隐藏时发生,而不是在工作表的行被隐藏时发生。

有人知道为什么会这样吗?尽管有过滤器,有没有办法正确重新应用数组?如果没有,有没有办法暂时移除过滤器,进行更改,然后将相同的过滤器放回原位?或者只是一种不牺牲速度的更好方法?

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 您可以删除过滤器并在完成后将其应用回来吗?另外,试试stackoverflow.com/documentation/excel-vba/1107/…
  • 我考虑过删除过滤器并重新应用它,但我不知道如何获取有关当前过滤器的信息。而且我已经关闭了屏幕更新和计算,我只是在禁用事件的情况下尝试了它,它并没有明显更快。
  • 这个问题不是那个问题的重复。实际问题是 Excel 错误导致将数据设置为过滤范围的结果不正确。 有一种有效的解决方法:将变量数组写入临时未过滤范围,然后将数据从后者写入目标范围。见Excel 2013 VBA Bug when copying variant array to range of cells in a filtered table

标签: arrays excel autofilter listobject vba


【解决方案1】:

我在另一篇帖子here 上找到了捕获自动过滤状态的代码。

Sub ReDoAutoFilter()
    Dim w As Worksheet
    Dim filterArray()
    Dim currentFiltRange As String
    Dim col As Integer

Set w = ActiveSheet

' Capture AutoFilter settings
With w.AutoFilter
    currentFiltRange = .Range.Address
    With .Filters
        ReDim filterArray(1 To .Count, 1 To 3)
        For f = 1 To .Count
            With .Item(f)
                If .On Then
                    filterArray(f, 1) = .Criteria1
                    If .Operator Then
                        filterArray(f, 2) = .Operator
                        filterArray(f, 3) = .Criteria2 'simply delete this line to make it work in Excel 2010
                    End If
                End If
            End With
        Next f
    End With
End With

'Remove AutoFilter
w.AutoFilterMode = False

' Your code here

' Restore Filter settings
For col = 1 To UBound(filterArray(), 1)
    If Not IsEmpty(filterArray(col, 1)) Then
        If filterArray(col, 2) Then
            w.Range(currentFiltRange).AutoFilter field:=col, _
            Criteria1:=filterArray(col, 1), _
            Operator:=filterArray(col, 2), _
            Criteria2:=filterArray(col, 3)
        Else
            w.Range(currentFiltRange).AutoFilter field:=col, _
            Criteria1:=filterArray(col, 1)
        End If
    End If
Next col
End Sub

一个已知问题是它无法找到捕获日期过滤器的方法,其中条件基于过滤器下拉菜单中树视图控件的选择。

【讨论】:

  • 谢谢!我认为这种解决方法对我有用,但我希望我一开始就知道出了什么问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
相关资源
最近更新 更多