2017-01-17 256 views
0

下面的代码是较大表单的一部分。我试图做的是:基于列的1 Excel VBA从筛选范围中选择单元格

  • 基于在列表框从2列并拉出从过滤的范围内的数据的用户所选项目

    • 在片材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 
      

      存放该位后代码I redimension数组并粘贴数据其他表。我的问题是,myRange.cells是从未经过滤的数据中进行选择。举例来说,我的过滤数据集包括第7,11,15和21行。当我过滤它并设置myRange时,它将突出显示4行加上标题。但是,当我使用单元格(2,2)时,我得到了未过滤的第2行第2列数据,而不是我的过滤数据集。我确信我错过了一些简单的东西,但我看不到它是什么。

  • 回答

    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 
    

    这可能在你的“主”的代码中使用如下

    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) 
    
    +0

    @mylesMoose,你通过它得到什么? – user3598756

    +0

    感谢您的回答。非常干净的方式去通过它。我没有关于过滤范围不连续。 – mylesMoose

    +0

    不客气。您可能希望将答案标记为已接受。谢谢! – user3598756