运行时错误9,下标超出范围

时间:2018-06-28 13:04:27

标签: excel vba excel-vba

我一直试图在VBA中创建一个函数来运行FindNext函数 n 次,以便可以找到 n th 个数字出现。

每当我尝试调用此函数时,都会出现错误:

  

运行时错误9:下标超出范围

我尝试过的代码如下:

Function FindZero(FindNum As Integer, InputRange As Range, N As Integer)
    Dim i As Integer
    Dim cell As Range

    For Each cell In InputRange.Cells
        For i = 0 To i < N
            cell = InputRange.FindNext(FindNum)
            MsgBox "The active cell address = " & cell.Address
        Next i
    Next cell
End Function

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

For循环的内容应如下所示:

Set cell = InputRange.Find.FindNext(FindNum)
If Not cell is Nothing Then MsgBox "The active cell address = " & cell.Address

代码中有3个错误:

  1. cell是一个Range对象。因此,使用了Set一词;
  2. 如果没有下一个值,请在显示MsgBox之前检查是否为空;
  3. FindNext之前应与Find一起使用(如@Jeeped的注释所述);

答案 1 :(得分:0)

以下是您应该使用的功能变体:

Public Function findNth(toFind As Variant, searchRange As Range, findOccurence As Long) As String
'returns the [findOccurence] occurence of [toFind] (number or text) within [searchRange]

    Dim n As Long, found As Range, firstMatch As Range
    Set found = searchRange.Cells.Find(toFind)
    If found Is Nothing Then
        'Debug.Print toFind & " not found"
        findNth = "" 'not found
        Exit Function
    End If
    Set firstMatch = found

    Do
        n = n + 1
        Debug.Print "Match#" & n & "/" & findOccurence & ": " & found.Address
        Set found = searchRange.FindNext(found)
        If found Is Nothing Or found = firstMatch Then
            'Debug.Print "(Only " & n & "/" & toFind & " occurrences were found)"
            findNth = "" 'not found
            Exit Function
        End If

    Loop While n <= findOccurence
    findNth = found.Address
End Function

用法示例:

此示例返回工作表{{1}上单元格22中值A2:E13 7 th 匹配项的单元格地址}。

myWkSheet

更多信息:

相关问题