【问题标题】:Get unique list with filtered range of another column获取具有另一列过滤范围的唯一列表
【发布时间】:2021-08-02 10:06:36
【问题描述】:

我需要为 A 列中的每个唯一值提取 B 列中的唯一值。 我有一个帖子中的代码,但它列出了整个列的唯一值。 我想要的只是那些与我提供的过滤条件相关联的唯一值。

我需要将这些唯一值移动到一个数组中,并将其用于另一个工作表计算。 我到目前为止的代码如下。

Sub test()
    Dim TestRg As Excel.Range
    Dim Array1(200) As Variant
    Dim i, j As Integer
    i = 1
    
    Set TestRg = Range("L1:L181")
    TestRg.AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:= _
        ActiveCell, Unique:=True
    For Each C In TestRg.SpecialCells(xlCellTypeVisible)
    If Not (C) Is Nothing Then
        Array1(i) = C.Value
        i = i + 1
    End If
    Next C
    j = i - 1
    i = 1

    
    For i = 1 To j
    Debug.Print Array1(i)
    Next
End Sub

请帮忙。

【问题讨论】:

  • 参见this,了解如何创建独特的价值
  • “B 列中的唯一值,A 列中的每个唯一值”的概念有点奇怪。将您的文字解释与您的代码相结合,我们是否应该理解您需要在对列“L:L”应用高级过滤范围后从“A:B”列中提取一个数组,使用标准并返回唯一值?
  • 我正在做的事情如下。应用自动过滤器并在 col E 中选择一个值。 Col L 包含许多行,其中许多值重复。所以使用 col L 列出所有唯一值并将其发送到 SQL 服务器进行查询。通过对@PGSystemTester 下面提供的代码进行一些修改解决了问题。

标签: excel vba


【解决方案1】:

此宏将捕获活动表 A 列中所有可见单元格的所有不同值,并在 B 列中设置值。如果行隐藏在 B 列中,则可能无法按您的预期显示。

Sub findtheVisibleUniqueValues()
Dim sRange As Range, aCell As Range, i As Long
Dim ws As Worksheet
    Set ws = ActiveSheet
    
ReDim zRay(1 To 1, 1 To 1)
i = 1

Set sRange = Intersect(ws.Range("A:A"), ws.UsedRange)

For Each aCell In sRange.Cells
    If aCell.EntireRow.Hidden = True Then
        'skip
    ElseIf Not (checkForMatch(aCell.Value, zRay)) Then
            ReDim Preserve zRay(1 To 1, 1 To i)
            zRay(1, i) = aCell.Value
            i = i + 1
    End If

Next aCell

'Your array is complete.
'This will insert to Column B (note if rows are hidden, it may not display correctly)

ws.Range("B1").Resize(UBound(zRay, 2), 1).Value = Application.WorksheetFunction.Transpose(zRay)

End Sub



Private Function checkForMatch(theValue As Variant, theArray()) As Boolean
Dim g As Long, j As Long

For j = LBound(theArray) To UBound(theArray)
    For g = LBound(theArray, 2) To UBound(theArray, 2)
        If theValue = theArray(j, g) Then
            checkForMatch = True
            Exit Function
        End If
    Next g
Next j

End Function

【讨论】:

  • 谢谢。它只需少量修改和一些添加代码即可工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多