无法更新数组中的值 VBA Excel

Value in array cannot be updated VBA Excel

我正在尝试获取范围与文本的第 n 个相似之处。 Similarity 函数是 return 两个文本之间的百分比相似度。

Function SimilarText(ByVal CompareText As String, _
                    ByRef TargetCompare As Range, _
                    Optional ByVal RankSimilarity As Integer = 1) As Long

Dim compareResults() As Long
ReDim compareResults(RankSimilarity)
Dim simiResult As Single
Dim smallestIndex As Integer
Dim result As String
Debug.Print (CompareText)

For Each cell In TargetCompare
    simiResult = Similarity(cell.Value, CompareText)
    Debug.Print (simiResult)
    If simiResult > Application.Min(compareResults) Then
        smallestIndex = Application.Match(Application.Min(compareResults), compareResults, 0) - 1
        Debug.Print ("Index:" & smallestIndex)
        compareResults(smallestIndex) = CLng(simiResult)'//This doesnt seem to do anything. I tried without the conversion but still nothing.
        Debug.Print ("Smallest after update:" & compareResults(smallestIndex)) '//This always 0
    End If
Next cell

    SimilarText = Application.Min(compareResults) '//So this is also alway 0

End Function

我希望数组元素会在每个单元格之后更新,例如 '(0.22,0.44) 但结果似乎总是 0。

您的数组 compareResults() 定义为 Long,并且仅适用于整数。

Long data type (Visual Basic)

将数据类型更改为允许小数的类型。

此外,在行 compareResults(smallestIndex) = CLng(simiResult) 中,您强制将数字变为长整数。使用其他东西,否则它会保存一个长整数。