|在本文中,我们将创建一个自定义函数来计算定义范围内的唯一值。

此示例的原始数据由行中的随机数组成。在此示例中,我们要计算每一行中唯一数字的数量。

ArrowRaw

我们创建了“ CountUniqueValues”自定义函数来查找该行中唯一数字的计数。此函数将范围作为输入,并返回唯一的数字计数。

ArrowOutput

逻辑解释

我们创建了自定义函数“ CountUniqueValues”来获取唯一数字的计数。在此自定义函数中,我们创建了集合对象的对象。此收集对象用于创建唯一编号列表。一旦获得唯一编号列表,便可以获取集合中的项目计数。

代码说明

之所以使用Application.Volatile,是因为它将在工作簿中每次更改单元格值时重新计算。

On Error Resume Next用于处理错误。

请遵循以下代码

Option Explicit

Function CountUniqueValues(InputRange As Range) As Integer

Dim CellValue As Variant, UniqueValues As New Collection

Application.Volatile

'For error Handling

On Error Resume Next

'Looping through all the cell in the defined range

For Each CellValue In InputRange

UniqueValues.Add CellValue, CStr(CellValue)  ' add the unique item

Next

'Returning the count of number of unique values

CountUniqueValues = UniqueValues.Count

End Function

如果您喜欢此博客,请在Facebook和Facebook上与您的朋友分享。

我们很希望收到您的来信,请让我们知道我们如何才能改善我们的工作并使您的工作更好。写信给我们[email protected]