excel - 在不清除过滤器的情况下设置 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
解决方案
推荐阅读
- javascript - 将 if else 转换为 switch (Typescript)
- amazon-web-services - AWS MSK 使用的 EBS 存储卷类型
- ruby - RSpec:我们可以配置一个期望返回两个不同的值吗?我想测试重试机制
- jpeg - JPEG 编码。如何使用 Huffman 算法对 RLE(AC) 进行编码
- azure-devops - 扩大管道数量 AzureDevOps
- ruby-on-rails - 如何使用现有记录删除祖先
- grafana - 如何将 JavaScript(例如 Google Analytics)包含到 Grafana 中?
- websphere - IBM ACE - 覆盖基本 URL (RestRequestNod)
- android - Android Volley:为什么这两个请求中的第二个请求超时失败?
- c# - 诊断服务器端 Blazor 内存问题