Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 views
in Technique[技术] by (71.8m points)

excel - UDF using FindNext seems to abort without warning

I have the following user-defined function, which attempts to find the nth non-empty cell in a range:

Option Explicit

Function finn_prioritert_oppgave(nummer As Long) As String

  Dim i As Long, r As Range, c As Range

  Set r = Range(PDCA.Range("L9"), PDCA.Range("L1048576").End(xlUp))
  i = 1

  Set c = r.Find(What:="*", LookIn:=xlValues, LookAt:=xlWhole)

  While (Not c Is Nothing) And (Intersect(c, PDCA.Rows(9)) Is Nothing) And (i < nummer)

    Debug.Print c
    Set c = r.FindNext(c)
    Debug.Print c
    Debug.Print CBool(c Is Nothing)
    i = i + 1

  Wend

  If c Is Nothing Then
    finn_prioritert_oppgave = "#N/A"
  Else
    finn_prioritert_oppgave = c.Offset(0, -10).Value
  End If

End Function

Running it with 1 as the argument works fine, presumably because it doesn't enter the While-loop and hit the FindNext, but running it with any larger value as the argument causes the cell it is called from to display a #VALUE!-alert.

Looking at what is displayed in my immediate-window is also really strange, as the two Debug.Print messages after doing the FindNext doesn't print, although I get no alerts.

The output I get in the immediate window, with the UDF invoked with 2 as its argument is simply an x:

enter image description here
The area the function is called from looks like this (the first line is the UDF invoked with 1 as the argument, the second is it invoked with 2 as the argument), while the area containing data looks like this.

So what I wonder is, why does FindNext fail to find the second non-empty cell in the range, and why does the function abort without any warning?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

FindNext doesn't work in UDFs. You have to simply repeat the original Find operation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...