繁体   English   中英

Excel VBA从过滤范围中选择单元格

[英]Excel VBA selecting cells from filtered range

下面的代码是较大形式的一部分。 我想做的是:

  • 在工作表2(数据列表)上,基于第1列过滤数据
  • 根据用户在列表框中选择的项目,从特定行的第2列和第3列的过滤范围中提取数据,然后粘贴到工作表1(JHA)中
  • 我知道数据仅在过滤后的列表中位于哪行,因为我将其存储在2D数组中dataArr

     Sheets("Data List").Select With Worksheets("Data List").Range("A1", Sheets("Data List").Range("C1").End(xlDown)) .AutoFilter field:=1, Criteria1:=UserForm1.ListBox3.List(k) 'filter data based on user listbox selection For j = 0 To UserForm1.ListBox1.ListCount - 1 'Find user selection from LB3 in LB1 to match filtered data order If UserForm1.ListBox3.List(k) = UserForm1.ListBox1.List(j) Then Exit For Next j For h = 0 To UBound(dataArr, 2) If dataArr(j, h) = 1 Then 'If the user has selected they want this data then add it to the array Set myRange = Sheets("Data List").AutoFilter.Range().SpecialCells(xlCellTypeVisible) myRange.Select arr1(l) = myRange.Cells(h + 2, 2) arr2(l) = myRange.Cells(h + 2, 3) l = l + 1 End If Next h .AutoFilter 

    在这段代码之后,我重新定义了数组并将数据粘贴到另一张纸上。 我的问题是myRange.cells正在从未过滤的数据中进行选择。 例如,说我的过滤数据集包括第7、11、15和21行。当我过滤并设置myRange时,它突出显示了4行和标题。 但是,当我使用cells(2,2)时,我得到的是未过滤的第2行第2列数据,而不是过滤后的数据集。 我确定我缺少一些简单的东西,但是我看不到它是什么。

过滤范围可以是(不,几乎总是!)一个不连续的范围,因此您必须遍历该范围并指定第n个值

您可能要使用此功能:

Function GetFilteredCellsNthValue(filteredRng As Range, nthVal As Long) As Variant
    Dim iVal As Long, Dim cell As Range

     iVal = 1
    ForEach cell in filteredRng
        If iVal = nthVal Then Exit For
        iVal = iVal + 1
    Next
    GetFilteredCellsNthValue = Iif(iVal>filteredRng.Count, CVErr(xlErrValue), cell.Value)
End Function

可以在您的“主”代码中使用该代码,如下所示

arr1(l) = GetFilteredCellsNthValue( .Resize(,1).Offset(.Rows.Count - 1,1).SpecialCells(xlCellTypeVisible)), h + 2)

arr2(l) = GetFilteredCellsNthValue( .Resize(,1).Offset(.Rows.Count - 1,2).SpecialCells(xlCellTypeVisible)), h + 2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM