Link to home
Start Free TrialLog in
Avatar of mskralik
mskralik

asked on

Random number generation in MS Word

Dear Expert,
Is there a random number that can be referenced or activated upon printout or macrobutton activation so that the number can be used as a Reference Bookmark to determine a simple yes/no outcome? If so, how do you write the code?
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Not sure that I understand exactly what you mean, but let's start with this.
Sub RandomBookmarkData()
Dim number As Integer
Dim rng As Range
Randomize
number = Rnd * 10000
Set rng = ActiveDocument.Bookmarks("MyBookmark").Range
rng.Text = Format(number, "0000")
ActiveDocument.Bookmarks.Add "MyBookmark", rng
End Sub

Open in new window

Avatar of mskralik
mskralik

ASKER

Hi Graham,

Is it possible to just generate a random number as a field updates at the time of printing? I' thinking something like:

{ If {{Rnd} * 1000} > "500" "Yes" "No"}

Thanks
I'm afraid there isn't a randomising feature in Word fields. You will have to use VBA.
Hi Graham,

Thanks for the guidance. Ok, so I try to run the macro as you have it, and the editor pops up with this line of code highlighted -

Set rng = ActiveDocument.Bookmarks("RandomNumber").Range

Wnen I place the cursor over the "Set rng" portion of the code, a box pops up that says, "rng = Nothing".
Any ideas?

Thanks
Is there an error message?
Yes...sorry that I did not include this earlier.

Run-time error '5941':

The requested member of the collection does not exist.
ASKER CERTIFIED SOLUTION
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry,
Is it possible for the code to automatically assign and populate into the bookmark called "RandomNumber"?
Hi Graham,

Thanks for your help, I was able to get this working.

-Michael