【问题标题】:numbers of unique entries in range, VBA范围内唯一条目的数量,VBA
【发布时间】:2023-04-04 01:07:01
【问题描述】:

在尝试执行以下操作时,我总是收到类型不匹配错误或除以零错误:我只想计算一个范围内的唯一条目数,该范围内的条目是“类”文本:

startRow = 3
startColumn = 1
col = "A"
Set topCell = Cells(startRow, startColumn)
Set bottomCell = Cells(Rows.Count, startColumn)
If IsEmpty(bottomCell) Then Set bottomCell = bottomCell.End(xlUp)
Set selectRows = Range(col & topCell.Row & ":" & col & bottomCell.Row)
nRows = WorksheetFunction.CountA(selectRows)

test = WorksheetFunction.SumProduct(WorksheetFunction.IsText(selectRows) / WorksheetFunction.CountIf(selectRows, selectRows))

我在测试计算中有一个错误,但我不明白。非常感谢一些帮助

非常感谢

BR 马丁

【问题讨论】:

  • 虽然IsText 会在工作表函数中使用Range 对象,但我认为它不会在VBA 中接受Range?我一直在玩它,但无法在 VBA 中获得与工作表函数相同的行为

标签: vba range unique duplicate-removal


【解决方案1】:

您的第一个问题是您的test 计算中的WorksheetFunction.CountIf(selectRows, selectRows) 部分。当没有重复时,这将导致除以零错误。输入工作表时也会发生这种情况,因此您要么需要更改逻辑,要么先测试这种情况。

我相信您的Type Mismatch 问题是由WorksheetFunction.IsText(selectRows) 段引起的。我无法弄清楚是什么原因造成的,但正如我在 cmets 中提到的,我认为 IsText() 函数可能不会像在单元格中键入时那样在 VBA 中占用一个范围。

我可能会以不同的方式解决这个问题。这是我在 SO Count unique values in Excel 其他地方找到的一个示例 这主要有工作表公式,但是您可能可以适应 1 个带有 VBA 代码的答案。

另一种选择是创建一个集合并计算元素的数量

Sub CountUnique()
Dim Col As New Collection
Dim i As Integer

On Error Resume Next

For i = 3 To 10
    Col.Add Sheet1.Cells(i, 1).Value, Sheet1.Cells(i, 1).Value
Next

MsgBox Col.Count

On Error GoTo 0
End Sub

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多