【问题标题】:VBA function returning '#VALUE!'VBA 函数返回“#VALUE!”
【发布时间】:2018-10-08 11:09:54
【问题描述】:
Public Function MostOccuring(items() As Variant) As String
    Dim count() As Integer
    Dim strings() As Object
    Dim Index As Integer
    For Index = 0 To items.Length - 1
        If srings.Exists(items(Index)) Then
            count(strings.IndexOf(items(Index))) = 1 + count(strings.IndexOf(items(Index)))
        Else
            count(Index) = 1
            strings(Index) = items(Index)
        End If
    Next
    End
    MostOccuring = strings(count.IndexOf(count.Max()))

End Function

这是我最常用的功能

我是这样称呼它的

它返回“#VALUE!”。为什么?它应该返回出现次数最多的单元格字符串。谢谢。

【问题讨论】:

  • If srings.Exists(items(Index)) 应该是 If strings.Exists(items(Index))。最重要的是你的代码,在Sub 上面放Option Explicit,它将防止这些错误发生。
  • 顶部的MostOccuring 语句到底应该做什么?在我看来,这将是一个非法的声明。如果您的代码无法编译(调试 > 编译 VBProject),它肯定不会运行。
  • 这可以通过现有函数来完成:=INDEX(C:C,MODE(MATCH(C2:C10,C:C,0)))
  • 为了帮助诊断这些事情,它有助于在行上设置断点,以便代码在执行时停止在该行,从而允许您在 VBE 的“Locals”窗格中检查变量的值。
  • ...或从 Sub 调用您的函数,以便您更轻松地调试它

标签: arrays excel vba mode


【解决方案1】:

你也可以试试这样的……

Public Function MostOccuring(items As Range) As String
Dim cell As Range
Dim dict, it
Dim maxCnt As Long

Set dict = CreateObject("Scripting.Dictionary")
For Each cell In items
    If Not dict.exists(cell.Value) Then
        dict.Item(cell.Value) = 1
    Else
        dict.Item(cell.Value) = dict.Item(cell.Value) + 1
    End If
Next cell

For Each it In dict.keys
    If dict.Item(it) > maxCnt Then
        maxCnt = dict.Item(it)
        MostOccuring = it
    End If
Next it
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多