vba: get unique values from array

前端 未结 9 2256
北恋
北恋 2020-11-22 15:30

Is there any built-in functionality in vba to get unique values from a one-dimensional array? What about just getting rid of duplicates?

If not, then how would I get

9条回答
  •  一个人的身影
    2020-11-22 15:56

    No, VBA does not have this functionality. You can use the technique of adding each item to a collection using the item as the key. Since a collection does not allow duplicate keys, the result is distinct values that you can copy to an array, if needed.

    You may also want something more robust. See Distinct Values Function at http://www.cpearson.com/excel/distinctvalues.aspx

    Distinct Values Function

    A VBA Function that will return an array of the distinct values in a range or array of input values.

    Excel has some manual methods, such as Advanced Filter, for getting a list of distinct items from an input range. The drawback of using such methods is that you must manually refresh the results when the input data changes. Moreover, these methods work only with ranges, not arrays of values, and, not being functions, cannot be called from worksheet cells or incorporated into array formulas. This page describes a VBA function called DistinctValues that accepts as input either a range or an array of data and returns as its result an array containing the distinct items from the input list. That is, the elements with all duplicates removed. The order of the input elements is preserved. The order of the elements in the output array is the same as the order in the input values. The function can be called from an array entered range on a worksheet (see this page for information about array formulas), or from in an array formula in a single worksheet cell, or from another VB function.

提交回复
热议问题