简体   繁体   English

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

[英]Runtime error 9, subscript out of range

I've been trying to create a function to run the FindNext function n times in VBA so that I can find the n th occurrence of a number within a range. 我一直在尝试创建一个函数以在VBA中运行nFindNext函数,以便可以找到某个范围内数字的 n 出现。

Whenever I try to call this function I get the error: 每当我尝试调用此函数时,都会出现错误:

Runtime error 9: Subscript out of range 运行时错误9:下标超出范围

The code that I have tried is listed below: 我尝试过的代码如下:

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

I would appreciate your help 谢谢您的帮助

The content of the For-loop should be like this: For循环的内容应如下所示:

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

There are 3 errors in the code: 代码中有3个错误:

  1. cell is a Range object. cell是一个Range对象。 Thus, the word Set is used; 因此,使用单词Set
  2. If there is no next value, make a check for not nothing, before showing the MsgBox ; 如果没有下一个值,请在显示MsgBox之前检查是否为MsgBox
  3. The FindNext should be used with Find before (as noted in the comments from @Jeeped); FindNext应该与之前Find一起使用(如@Jeeped的注释中所述);

Here is a variation on your function that should work for you: 这是您应该使用的功能变体:

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

Example Usage: 用法示例:

This example returns the cell address of the 7 th match of the value 22 , within cells A2:E13 on worksheet myWkSheet . 本示例在工作表myWkSheet单元格A2:E13返回值22的第7 匹配项的单元格地址。

Sub testFind()
    Dim cellAddy As String
    cellAddy = findNth(22, Sheets("myWkSheet").Range("A2:E13"), 7)

    If cellAddy = "" Then
        MsgBox "Match not found"
    Else
        MsgBox "Found in cell: " & cellAddy
    End If
End Sub

More Information: 更多信息:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM