![]() |
|
|
|
#1
|
|||
|
|||
|
Code:
Sub test()
Dim x As Integer
For x = 0 To 3
MsgBox (ReturnRandomNumber(0, 3, x))
Next x
End Sub
Public Function ReturnRandomNumber(lower As Integer, upper As Integer, turn As Integer) As String
Dim n As Integer, arr() As Variant
Redo:
n = Int((upper - lower + 1) * Rnd + lower)
ReDim Preserve arr(turn)
''' I want to store every n to check if the random number generated is repeated
For Each a In arr
If a = n Then GoTo Redo
Next a
''' Within this function, the Array arr() does not store every n
arr(turn) = n
ReturnRandomNumber = n
End Function
But it does not work within a public function. |
|
#2
|
||||
|
||||
|
From the Word vba help file:
This array is fixed or temporarily locked (Error 10) You attempted to assign a value to a Variant variable containing an array, but the Variant is currently locked. For example, if your code uses a For Each...Next loop to iterate over a variant containing an array, the array is locked on entry into the loop, and then released at the termination of the loop ... Use a For...Next rather than a For Each...Next loop to iterate. When an array is the object of a For Each...Next loop, you can read the array, but not write to it.
__________________
Cheers, Paul Edstein [Fmr MS MVP - Word] |
|
#3
|
|||
|
|||
|
Code:
Sub test()
Dim x As Integer
For x = 0 To 3
MsgBox (ReturnRandomNumber(0, 3, x))
Next x
End Sub
Public Function ReturnRandomNumber(lower As Integer, upper As Integer, turn As Integer) As String
Dim n As Integer, arr() As Variant
Redo:
n = Int((upper - lower + 1) * Rnd + lower)
Debug.Print (n)
ReDim Preserve arr(turn)
For a = lower To upper
If arr(a) <> "" Then
If arr(a) = n Then GoTo Redo
Else
Exit For
End If
Next a
arr(turn) = n
ReturnRandomNumber = n
End Function
|
|
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
Complex array formula
|
andrei | Excel | 9 | 02-03-2012 03:40 AM |
| How to capture start and ending Ref. Nos. in an array | KIM SOLIS | Excel | 5 | 09-07-2011 07:43 AM |
| Look up an array based on user input | johnsmb | Excel | 2 | 01-07-2011 01:12 PM |
| outlook programmatically read an attachment into byte array | chriskaza81 | Outlook | 0 | 11-19-2010 01:03 AM |
Array into ComboBox + Macro-Text into ActiveDocument
|
Vivi | Word VBA | 1 | 01-27-2010 07:03 AM |