arrays - 使用具有多个值的筛选列中的唯一值填充数组

标签 arrays excel vba

我正在尝试使用已过滤的 Excel 表格中的列中的值填充数组。

在此列中,值可能会出现多次,但我需要返回唯一值,而不是每个值的所有出现位置。

Column F
a
a
a
b
c
c
a
b
d

该数组将具有可变长度,并且根据示例列将具有以下元素:{a, b, c, d}

数组的长度无法固定,因为我的函数使用长度不同的过滤表。有时可能只有一个唯一值,有时可能有三个。

我需要这样做,因为我的数组将用于确定包含“...”和数组的电子邮件的主题。

如何将列中的唯一值提取到数组中?

最佳答案

使用 Scripting.Dictionary

您可以使用 sht.Cells(sht.Rows.Count, "F").End(xlUp).Row 选择列中的所有数据,然后使用 脚本。字典来查找您的独特值(value)观。代码如下:

'Main Routine
Sub MyMacro()
    Dim sht As Worksheet
    Dim column As Range
    Dim LastRow As Long
    Dim uniqueValues() As Variant

    Set sht = ActiveSheet 'Set your sheet here

    LastRow = sht.Cells(sht.Rows.Count, "F").End(xlUp).Row
    Set column = Range("F1:F" & LastRow)
    uniqueValues = getUniqueValues(column)
    'Do what you need to do with your values [...]
End Sub

'Return unique values from a Range
Function getUniqueValues(column As Range)
    Dim dict As New Scripting.Dictionary ' requires "Microsoft Scripting Runtime"
    Dim cell As Range

    For Each cell In column
        dict(cell.Value) = "1"
    Next

    'A double Transpose will put your data in an Array() format
    getUniqueValues = Application.Transpose(Application.Transpose(dict.Keys))
End Function

如果您不想导入 Microsoft Scripting Runtime,请使用此代码进行 dict 声明:

    'If you don't want to import Scripting Runtime, use this code
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")

Note: This is tested and works perfectly.

我希望这会有所帮助。

关于arrays - 使用具有多个值的筛选列中的唯一值填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58300419/

相关文章:

php - 使用 PHP 将数据排序为多维分层数组

当表具有 ID 或类时,JQuery 将表导出到 Excel 时出错

php - 自动调整 Excel 列宽

python - 在 Pandas/Python 中格式化连接的列。

vba - 工作表更改立即添加()而不自动更新

php - 从多维数组的子数组中删除不需要的元素

c++ - 在 C++ 中用整数填充固定大小的 char 数组

java - 自动向数组添加元素

excel - VBA isString vs isNumeric

class - 从 VBA 函数返回新类对象的 "right"方法是什么?