繁体   English   中英

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

[英]Runtime error 9, subscript out of range

我一直在尝试创建一个函数以在VBA中运行nFindNext函数,以便可以找到某个范围内数字的 n 出现。

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

运行时错误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

谢谢您的帮助

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之前检查是否为MsgBox
  3. FindNext应该与之前Find一起使用(如@Jeeped的注释中所述);

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

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

用法示例:

本示例在工作表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

更多信息:

暂无
暂无

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

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