Excel VBA从过滤范围

时间:2017-01-17 21:11:49

标签: vba excel-vba excel

以下代码是较大表单的一部分。我想做的是:

  • 在表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行加上标题。但是,当我使用单元格(2,2)时,我得到未经过滤的第2行第2列数据,而不是我的过滤数据集。我确定我错过了一些简单的东西,但我看不出它是什么。

1 个答案:

答案 0 :(得分:0)

过滤范围可以(好吧,它几乎总是!)是一个不连续的范围,所以你必须遍历它并调整第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

这可以用在你的" main"代码如下

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)
相关问题