Excel vba:.find函数返回运行时错误91

您所在的位置:网站首页 berkeley的意思 Excel vba:.find函数返回运行时错误91

Excel vba:.find函数返回运行时错误91

2023-08-14 08:16| 来源: 网络整理| 查看: 265

这里是一个函数,它会直接告诉你的行号。这与您在构建函数中使用以获得最大值然后再次找到它的方法相反!

Function GetMaxRow(ByRef myRange As Range) As Long Dim aCell As Range Dim maxVal As Double Dim maxRow As Long maxVal = Application.WorksheetFunction.Min(myRange) maxRow = 0 For Each aCell In myRange If aCell.Value > maxVal Then maxRow = aCell.row maxVal = aCell.Value End If Next aCell GetMaxRow = maxRow End Function

您可能需要一些错误检查的代码添加到该函数的结果,例如,当函数返回0,那就意味着你没有通过它的范围超过1个细胞。

例子:

1 - 3.0 2 - 5.2 3 - 7.8 4 - 2.2 5 - 4.5 6 - 3.6 Dim rw as Long rw = GetMaxRow(ActiveSheet.Range("A1:A6")) ' >> rw = 3

编辑:

您查询的循环语句使用,因为节省时间的推测。下面是一个时间表,当然这将在不同的计算机上有所不同,但是你可以看到它是一个相当快的例程,除非你的数据集很大......而且这个操作的顺序与预期的一样是线性的,这意味着将范围加倍大约两倍所花费的时间。

2000 rows: 0.0050000s 4000 rows: 0.0099219s 8000 rows: 0.0196875s 16000 rows: 0.0392969s

测试了该单元格的值是随机双打0和1之间

编辑2:

您见顶那么的循环在一定范围内,而不是...我对速度感兴趣(慢)我写了相同的功能,但使用一个数组。范围被转换为数组,然后循环。这提供了〜10倍的速度提升!有关相同数据的代码和时间,请参见下文。

Function GetMaxRow(ByRef myRange As Range) As Long Dim i As Long Dim maxVal As Variant Dim maxRow As Long maxVal = Application.WorksheetFunction.Min(myRange) maxRow = 0 Dim myArray() As Variant myArray = myRange For i = 1 To myRange.Count If myArray(i, 1) > maxVal Then maxRow = i maxVal = myArray(i, 1) End If Next i GetMaxRow = myRange.Cells(maxRow).Row End Function

时序:

2000 rows: 0.0006250s 4000 rows: 0.0018750s 8000 rows: 0.0034375s 16000 rows: 0.0068750s


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3