下面是一个函数,它应该在1 and 10
之内的column A
之间返回一个随机值。它在查找随机值和退出循环方面工作正常,但在使用=Ang()
调用excel时,函数返回#Value!
,如下所示。
Function Ang()
i = 0
Do
i = Application.WorksheetFunction.RandBetween(1, 10)
Ang = i
MsgBox Ang
Loop While Application.WorksheetFunction.IfNa(Application.WorksheetFunction.Match(i, Worksheets("Sheet2").Range("A:A"), 0), 0)
End Function
答案 0 :(得分:0)
问题是WorksheetFunction.Match将在没有找到错误的情况下停止代码。
改为使用Application.Match
:
Function Ang() as Long
Dim i as Long
i = 0
Do
i = Application.WorksheetFunction.RandBetween(1, 10)
Ang = i
MsgBox Ang
Loop While Not IsError(Application.Match(i, Worksheets("Sheet2").Range("A:A"), 0))
End Function
或
Function Ang()
i = 0
Do
i = Application.WorksheetFunction.RandBetween(1, 10)
Ang = i
MsgBox Ang
Loop While Application.WorksheetFunction.CountIf(Worksheets("Sheet2").Range("A:A"), i)
End Function
答案 1 :(得分:0)
为什么不把它作为函数的参数,而不是在数字范围内进行硬连接?
Function NewRandom(R As Range, a As Long, b As Long) As Variant
'returns a random number in a,b which isn't in range R
Dim i As Long, k As Long, rand As Long
Dim c As Range
Dim avoid As Variant
Dim count As Long
ReDim avoid(a To b) As Boolean
For Each c In R.Cells
k = c.Value
If a <= k And k <= b Then
avoid(k) = True
count = count + 1
End If
Next c
If count = b - a + 1 Then 'error condition!
NewRandom = CVErr(xlErrValue)
Else
Do
rand = Application.WorksheetFunction.RandBetween(a, b)
Loop While avoid(rand)
NewRandom = rand
End If
End Function
用过:
该功能可防止无限循环。如果在B1中我使用了=NewRandom(A1:A7,1,5)
,那么将返回错误#VALUE!
。该代码假定从a
到b
的范围不是很大,以至于是一个重要的内存消耗。如果是,则数组avoid
可以替换为字典。