首页 > 解决方案 > 在不清除过滤器的情况下设置 Excel 范围的值

问题描述

所以我通常使用数组,因为这可以加快 VBA 中的处理速度。例如

'get data
values = dataRange.value

'Do some work on values array

'set data
dataRange.value = values

最近我们注意到,在 Excel 中执行相同的过程时,在带有过滤器的表上,Excel:

通过获取所有值来执行我们期望的 getter:

'get data
values = table.DataBodyRange.value

从第一个过滤的行开始执行 setter:

'set data
table.DataBodyRange.value = values 'Starts at the visible row?!

即使DataBodyRange.address显示范围超过所有数据,它也会这样做

我们当前的工作是保存过滤器首选项,清除过滤器,设置数据,然后重新应用过滤器。但是,这很慢,而且似乎毫无意义。有谁知道执行这项工作的更直接的方法?

解决代码:

Sub Commit()
  'Create list object of HFRR.
  Dim lo As ListObject
  Set lo = Datasheet.ListObjects("<<TableName>>")

  'WORK AROUND:
  'In VBA range.value will only work if filters are NOT applied. I.E. we can't change the data model without first unfiltering the data.
  'This is a bad UX so the work around is to save the filters in a cache, and reload these after the data is set.
  'VBA doesn't provide a method of saving autofilter choices, so instead we use:
  '  https://stackoverflow.com/questions/9489126/in-excel-vba-how-do-i-save-restore-a-user-defined-filter
  '=====================================================================================================================================
  'Save and clear filters
  Dim AutoFilterCache() As Variant
  SaveListObjectFilters lo, AutoFilterCache
  lo.AutoFilter.ShowAllData

    'Set the data
    dataRange.Value = data

  'Restore the filters
  RestoreListObjectFilters lo, AutoFilterCache
End Sub

标签: excelvbafilter

解决方案


推荐阅读