【问题标题】:Value in array cannot be updated VBA Excel数组中的值无法更新 VBA Excel
【发布时间】:2019-05-10 10:52:33
【问题描述】:

我正在尝试将范围与文本进行比较的第 n 个相似点。 Similarity 函数是返回两个文本之间的相似度百分比。

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)。您是否尝试过更改数据类型?此外,CLng 强制数字为长整数,而不是小数。
  • 我没有尝试更改我的数据类型。所以这就是问题所在。抱歉问了这么一个菜鸟问题。
  • 别说对不起。 我们所有人在我们的生活中都是菜鸟(甚至我们中的一些人还不是菜鸟。这里有很棒的程序员)。这是一个强制性阶段。

标签: arrays excel vba assign


【解决方案1】:

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

Long data type (Visual Basic)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    相关资源
    最近更新 更多