vba: get unique values from array

前端 未结 9 2250
北恋
北恋 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 16:08

    No, nothing built-in. Do it yourself:

    • Instantiate a Scripting.Dictionary object
    • Write a For loop over your array (be sure to use LBound() and UBound() instead of looping from 0 to x!)
    • On each iteration, check Exists() on the dictionary. Add every array value (that doesn't already exist) as a key to the dictionary (use CStr() since keys must be strings as I've just learned, keys can be of any type in a Scripting.Dictionary), also store the array value itself into the dictionary.
    • When done, use Keys() (or Items()) to return all values of the dictionary as a new, now unique array.
    • In my tests, the Dictionary keeps original order of all added values, so the output will be ordered like the input was. I'm not sure if this is documented and reliable behavior, though.

提交回复
热议问题