VBA Range.Find() function not working with large floating numbers

删除回忆录丶 提交于 2019-12-24 07:43:10

问题


I am writing code to lookup the highest dollar amount in a column and bring back the value as well as the value of cells in adjacent columns with 9 char in the target cell

When I set the range variable it shows the value of "12000.88" which works fine, however as soon as that value extends to over 9 digits "123000.55" the "set fnd" doesn't find it and the range variable is Nothing. I have tested many other things and have found the only difference is the length of the value

Sub Populate()

    Dim Fnd As Range    
    Set Fnd = Range("L:L").Find(WorksheetFunction.Large(Range("L:L"), 1), , xlValues)

End Sub

I have no problem with smaller numbers but I don't understand why this wouldn't work with larger numbers.


回答1:


The problem is in the different decimal separators that Excel and VBA are using. Thus, in the floating point values, there is a "hidden feature". The Find() function actually looks for a string and the double is "stringified" obviously not the correct way - with a comma and not with a dot. Consider parsing to string and replacing the comma with a dot to make it work:

Sub Populate()

    Dim foo As Range        
    Dim biggus As Double

    biggus = WorksheetFunction.Large(Range("A:A"), 1)
    Set foo = Range("A:A").Find(ReplaceCommas(biggus), , xlValues)

    Debug.Print foo.Address

End Sub

Function ReplaceCommas(valueAsString As Variant) As String

    Dim valueToReplace  As String
    valueToReplace = valueAsString
    ReplaceCommas = Replace(valueAsString, ",", ".")

End Function

The fact that the "feature", does not appear, when xlFormulas, is in the SearchIn parameter, is due to the fact, that xlFormulas converts the content of the cell to string, in order to search in it. E.g., if there is =SUM(A1+A2) and we are looking for 1+A, the only way to find it is to parse the content of the cell to String.



来源:https://stackoverflow.com/questions/58310151/vba-range-find-function-not-working-with-large-floating-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!