问题
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