VBAFIND函数找到了最小值为什么不能确定单元格?

Private Sub CommandButton1_Click()
Dim m As Integer, n As Integer, i As Integer, y As Single, rng As Range
Cells.Interior.Pattern = xlNone
m = Cells(Rows.Count, 2).End(xlUp).Row
For i = 1 To m
n = Cells(i, Columns.Count).End(xlToLeft).Column
y = Application.WorksheetFunction.Min(Range(Cells(i, "h"), Cells(i, n)))

Set rng = Range(Cells(i, "h"), Cells(i, n)).Find(y, , xlValues, xlWhole)
rng.Interior.ColorIndex = i
Next
End Sub
代码如上,调试的时候能找到最小值y,在确定单元格的时候却是nothing ,所以无法给要选定的单元格添加颜色,请教高手

'find方法LookIn参数选xlValues时是以单元格显示文本进行查询的,并不支持实际值查询。如果查询单元格为常量,可将LookIn参数改为xlFormulas,若为公式返回值,则代码更改为:
Private Sub CommandButton1_Click()
Dim m As Integer, n As Integer, i As Integer, y As Double, rng As Range, a As String
Cells.Interior.Pattern = xlNone
m = Cells(Rows.Count, 2).End(xlUp).Row
For i = 1 To m
n = Cells(i, Columns.Count).End(xlToLeft).Column
a = Cells(i, Columns.Count).End(xlToLeft).Address
a = Mid(a, 2, InStr(2, a, "$") - 2)
y = Application.WorksheetFunction.Min(Range(Cells(i, "h"), Cells(i, n)))
Columns("h:" & a).NumberFormatLocal = "G/通用格式"
Columns("h:" & a).EntireColumn.AutoFit
Set rng = Range(Cells(i, "h"), Cells(i, n)).Find(y, , xlValues, xlWhole)
rng.Interior.ColorIndex = i
Next
End Sub
温馨提示:答案为网友推荐,仅供参考
第1个回答  2021-02-16
代码没问题,只是,H列都会依次填充不同的颜色
这个和N有关
第2个回答  2021-02-17

这是由于浮点数的原因引起的。

建议在这种情况下,不要使用 y 作为“中转”方式来调用,直接把 Min 函数代入在这里即可:

Set rng = Range(Cells(i, "h"), Cells(i, n)).Find(Application.WorksheetFunction.Min(Range(Cells(i, "h"), Cells(i, n))), , xlValues, xlWhole)

追问

你好,我试了这个办法也不行,但是我今天测试的时候发现一个问题,就是如果y值是整数的时候就行,比如16,如果换成15.60就不行了,不知道什么原因,请帮忙分析一下,谢谢。

追答

所以说浮点数引起的问题!
刚才我已经测试了这段代码,改了几个浮点数,试过都成功了!
刚才又仔细看了你的代码,可能还与你的代码循环查找有关系(Excel 可以会记住上一次查找的地址)。那样子的话,那你应该把 Find 的参数 After 加上再试试看!比如让 After: = Cells(i, n)

第3个回答  2021-02-16
我也觉得代码没问题,只是测试的时候显示ring的值为零,另外点击运行后只选取了一行,且用黑色显示了
第4个回答  2021-02-16
不会呀,测试了好好的哟