簡體   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