[英]Runtime error 9, subscript out of range
我一直在尝试创建一个函数以在VBA中运行n次FindNext
函数,以便可以找到某个范围内数字的第 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个错误:
cell
是一个Range对象。 因此,使用单词Set
; MsgBox
之前检查是否为MsgBox
。 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
Find
方法 (Excel) FindNext
方法 (Excel)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.