excel - 如何使用 `UsedRange` 动态获取两个不连续过滤条件的范围(第一行除外)?

标签 excel vba autofilter

enter image description here

正如您在示例图片中看到的,我在 B 列上设置了自动筛选,并排除了值 B
我需要使用 UsedRange 和 SpecialCells(xlCellTypeVisible) 方法获取除第一行之外的可见范围。
我尝试了以下三个代码,但它要么添加额外的行,要么抛出错误:

Sub Get_Range_of_two_non_contiguous_filtered_criteria_except_First_Row()
 
    Dim ws As Worksheet, rng As Range
    Set ws = ThisWorkbook.ActiveSheet
 
    Set rng = ws.UsedRange.Offset(1).SpecialCells(xlCellTypeVisible)
    Debug.Print rng.Address                                                  'Addtional Row is added to rng ($A$2:$B$3,$A$6:$B$8)
 
    Set rng = Intersect(ws.Cells, ws.UsedRange.Offset(1).SpecialCells(xlCellTypeVisible))
    Debug.Print rng.Address                                                  'Addtional Row is added to rng $A$2:$B$3,$A$6:$B$8
 
    Dim crg As Range: Set crg = ws.UsedRange.SpecialCells(xlCellTypeVisible)
    Set crg = crg.Offset(1, 0).Resize(crg.Rows.Count - 1, crg.Columns.Count)    'Error: Application-defined or object-defined error
    Debug.Print crg.Address
 
End Sub

这是我发现它可以正常工作的唯一方法:

Dim LastRow As Long
LastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
Set rng = ws.Range("A2:B" & LastRow).SpecialCells(xlCellTypeVisible)
Debug.Print rng.Address

提前感谢您的所有帮助和评论。

最佳答案

下一部分是错误的:

    Dim crg As Range: Set crg = ws.UsedRange.SpecialCells(xlCellTypeVisible)
    Set crg = crg.Offset(1, 0).Resize(crg.Rows.Count - 1, crg.Columns.Count)    'Error: Application-defined or object-defined error
    Debug.Print crg.Address

在使用SpecialCells之前,您需要调整使用范围的大小。不连续范围不能以这种方式调整大小。

下一个改编的代码应该可以工作:

    Dim crg As Range: Set crg = ws.UsedRange
    Dim crgVS As Range
     Debug.Print crg.Resize(crg.rows.count - 1, crg.Columns.count).Offset(1).address
    Set crgVS = crg.Resize(crg.rows.count - 1, crg.Columns.count).Offset(1).SpecialCells(xlCellTypeVisible)
     Debug.Print crgVS.address

我(仅)建议您使用Range("A1").CurrentRegionUsedRange 在原始/新工作表上效果很好。它可能包括您以前使用它们的行/列,即使它们现在是空的。尝试对内部或现有范围下方的单元格进行着色,并检查 UsedRange 地址。而这种情况下的结果可能达不到你的期望......

关于excel - 如何使用 `UsedRange` 动态获取两个不连续过滤条件的范围(第一行除外)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74177517/

相关文章:

c# - EPPlus:检测并处理 "number stored as text"

arrays - 将完整的拆分数组放入 VBA 变量中

excel - 返回 Excel VBA 宏 OneDrive 本地路径 - 可能的潜在客户

vba - 用户类型未定义工作表 VBA

excel - 自动筛选,列格式为日期

date - VBA自动过滤器在Excel中按日期设置-不显示任何数据

arrays - 在 VBA 自动筛选中使用字符串数组作为条件

c# - 如何从现有的 excel 文件中读取单元格值

vba - 在运行调用该模块的程序后访问另一个模块中模块的变量?

excel - 加载所有动态加载 HTMLTable - VBA