我一直试图在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
感谢您的帮助
答案 0 :(得分:0)
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
之前检查是否为空; 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
Find
Method(Excel)FindNext
Method(Excel)