Vba word случайное число

In MS EXCEL VBA I have for many years used

lowerbound=some figure
upperbound=some other figure
m=Int((upperbound-lowerbound+1)*Rnd +lowerbound)

I put this in a WORD macro and it did not work; it gave the same number for m every time I ran it.

Peter O.'s user avatar

Peter O.

31.9k14 gold badges81 silver badges95 bronze badges

asked Mar 30, 2017 at 21:19

davidmorley's user avatar

2

I don’t quite understand it, but if I split the expression for m into smaller expressions and combined the expressions later, then it worked.

answered Mar 31, 2017 at 14:39

davidmorley's user avatar

Генератор случайных чисел в VBA Excel. Функция Rnd, оператор Randomize, функция рабочего листа RandBetween. Синтаксис, параметры, примеры кода.

Rnd – это функция, которая возвращает значение типа Single, содержащее псевдослучайное число меньшее 1, но большее или равное нулю.

Псевдослучайное число отличается от случайного тем, что оно получено с помощью алгоритма, который, в любом случае, подчиняется какой-либо закономерности. Для решения большинства, а возможно и всех, задач в VBA Excel псевдослучайное число можно считать случайным.

Синтаксис

Rnd[(Число)]

Число – необязательный параметр, определяющий алгоритм вычисления псевдослучайного числа. Зависимость случайного числа от этого параметра:

Число Возвращаемое значение
Меньше нуля Одно и то же псевдослучайное число каждый раз, как результат использования параметра Число в качестве начального значения для алгоритма
Больше нуля Каждое следующее число в псевдослучайном порядке
Равно нулю Самое последнее псевдослучайное число, созданное функцией Rnd
По умолчанию Каждое следующее число в псевдослучайном порядке

Для любого параметра Число создается одна и та же последовательность чисел, так как каждый последующий вызов функции Rnd использует предыдущее значение в качестве начального для следующего псевдослучайного числа в последовательности.

Функция Rnd – это и есть простейший генератор случайных чисел в VBA Excel, возвращающий значения в интервале 0<=Rnd<1.

Чтобы повысить «случайность» псевдослучайных чисел, возвращаемых функцией Rnd, используется оператор Randomize.

Оператор Randomize

Randomize – это оператор, который инициализирует генератор случайных чисел функции Rnd, задавая начальное число для генерации первого псевдослучайного числа.

Синтаксис

Randomize[Число]

Число – необязательный параметр, задающий начальное число для генерации. Если параметр Число опущен, используется значение, возвращенное системным таймером.

При повторном использовании в VBA Excel оператора Randomize с тем же значением аргумента Число предыдущая последовательность не повторяется.

Для повторения предыдущей последовательности случайных чисел необходимо непосредственно перед оператором Randomize с тем же значением аргумента Число вызвать функцию Rnd с отрицательным аргументом.

WorksheetFunction.RandBetween

RandBetween – функция рабочего листа, возвращающая целое случайное число в пределах заданного диапазона значений.

Синтаксис

WorksheetFunction.RandBetween(Arg1, Arg2)

  • Arg1 – наименьшее целое число, которое возвращает функция рабочего листа RandBetween (обязательный параметр);
  • Arg2 – наибольшее целое число, которое возвращает функция рабочего листа RandBetween (обязательный параметр).

Примеры записи строк с WorksheetFunction.RandBetween в VBA Excel (присвоение случайного числа переменной):

a = WorksheetFunction.RandBetween(65, 15)

a = WorksheetFunction.RandBetween(5, 145)

Если данную функцию вставить в ячейку рабочего листа, например: =СЛУЧМЕЖДУ(25;55), случайное число будет обновляться при каждом пересчете листа.

Примеры с Rnd и Randomize

Пример 1
Запускаем генератор случайных чисел функции Rnd с разными параметрами и выводим результаты на рабочий лист Excel:

Sub Primer1()

Dim i As Byte

  Cells(1, 1) = «Rnd(-5)»

    For i = 2 To 5

      Cells(i, 1) = Rnd(5)

    Next

  Cells(1, 2) = «Rnd(3)»

    For i = 2 To 5

      Cells(i, 2) = Rnd(3)

    Next

  Cells(1, 3) = «Rnd(0)»

    For i = 2 To 5

      Cells(i, 3) = Rnd(0)

    Next

End Sub

Получаем следующий результат:

Случайные числа, возвращаемые функцией Rnd с разными аргументами

Пример 2
Повторное использование оператора Randomize с тем же значением аргумента Число:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Sub Primer2()

Dim i As Byte

  Cells(1, 1) = «Последовательность 1»

  Rnd (1)

  Randomize 4

    For i = 2 To 5

      Cells(i, 1) = Rnd

    Next

  Cells(1, 2) = «Последовательность 2»

  Randomize 4

    For i = 2 To 5

      Cells(i, 2) = Rnd

    Next

  Cells(1, 3) = «Последовательность 3»

  Rnd (1)

  Randomize 4

    For i = 2 To 5

      Cells(i, 3) = Rnd

    Next

End Sub

Строка кода Rnd (-1) обеспечивает генерацию последовательности случайных чисел сначала при повторных использованиях оператора Randomize.

Повторное использование оператора Randomize при генерации случайных чисел

Строка кода Randomize 4 перед заполнением второго столбца не влияет на работу функции Rnd, а заполнение последовательности для третьего столбца начинается заново благодаря строке Rnd (-1) перед оператором Randomize.

Пример 3
Создание генераторов случайных чисел для разных диапазонов. Исходим из того, что функция Rnd генерирует псевдослучайную последовательность из чисел меньше 1, но больше или равным 0.

Примеры с положительными случайными числами:

‘От 0 (включительно) до 10

  10 * Rnd

‘От 6 (включительно) до 7

  Rnd + 6

‘От 5 (включительно) до 10

  5 * Rnd + 5

Примеры с отрицательными случайными числами:

‘От -10 до 0 (включительно)

  10 * Rnd

‘От -10 до 10 (включительно)

  20 * Rnd + 10

‘От -10 до -5 (включительно)

  (5 * Rnd + 5)

Пример заполнения ячеек положительными и отрицательными случайными числами на листе Excel:

Sub Primer3()

Dim i As Byte

  Cells(1, 1) = «От 1 до 3»

    For i = 2 To 9

      Cells(i, 1) = 2 * Rnd + 1

    Next

  Cells(1, 2) = «От -5 до 5»

    For i = 2 To 9

      Cells(i, 2) = 10 * Rnd + 5

    Next

  Cells(1, 3) = «От -5 до -2»

    For i = 2 To 9

      Cells(i, 3) = 3 * Rnd 2

    Next

End Sub

Результат выполнения кода VBA Excel третьего примера:

Примеры положительных и отрицательных случайных чисел

Генератор случайных чисел с заполнением строк выделенного фрагмента в MS Word

 Представляю Вашему вниманию VBA макрос для заполнения выделенного фрагмента в MS Word случайными числами в пределах заданного значения

Public Sub FillTablewithRandomNumbers()
    Dim a As String
a = InputBox(«Введите величину напряжения под нагрузкой для элемента/блока, В (целую часть от дробной отделять запятой!)»)
    Dim rng As Range, SelEnd As Long, counter As Long
    Dim PrevPos As Long 
    ‘1. Запись в переменную конца выделения.
        ‘ С переменной быстрее работать, чем использовать объекты.
    SelEnd = Selection.End   
    ‘2. Присваиваем выделенному фрагменту имя «rng».
    Set rng = Selection.Range   
    ‘3. Превращаем выделенный фрагмент в курсор (аналогично, как при выделенном фрагменте
        ‘ нажать клавишу «стрелка влево»).
    rng.Collapse Direction:=wdCollapseStart   
    ‘4. Подсчёт строк.
    ‘ Цикл по всем строкам выделенного фрагмента.
    Do
        ‘1) В каждом витке цикла увеличиваем число в переменной «counter» на 1.
        counter = counter + 1       
        ‘2) Запоминание текущей позиции, чтбы понять, произошёл ли переход на следующую строку.
            ‘ Это нужно, если выделен фрагмент в конце файла.
        PrevPos = rng.Start       
        ‘3) Переход на следующую строку и присваиваем имя «rng» фрагменту, куда перешли.
        Set rng = rng.GoToNext(wdGoToLine)       
        ‘4) Проверка, произошёл ли переход на следующую строку (то есть не достигнут
            ‘ ли конец файла).
        If PrevPos = rng.Start Then
            Exit Do
        End If       
        ‘5) Проверка, не вышли ли мы за пределы выделенного фрагмента.
            ‘ Используется «>=», т.к. если в выделенном фрагменте последняя строка выделена целиком,
            ‘ то конец этой строки и начало следующей совпадают.
        If rng.Start >= SelEnd Then
            Exit Do
        End If
    Loop        
     Dim myRange As Range
    Set myRange = Selection.Range
    Selection.Cut    
    For i = 1 To counter
    x = Rnd()
    x = Round(Rnd / 6 + a, 2)
    Selection.Text = x
    Selection.MoveDown Unit:=wdLine, Count:=1
    Next i
End Sub

Популярные сообщения из этого блога

Batch projects in Photoshop with JavaScript (Пакетная обработка проектов в Photoshop с помощью JavaScript)

Изображение

 Всем доброго дня. (Good day everyone.) Хочу опубликовать несколько строчек кода и видео урок, о том как превращать набор операций .*atn в готовый JavaScript и применять пакетную обработку (I want to publish a few lines of code and a video tutorial on how to turn a set of operations *.atn file into ready-made JavaScript and apply batch processing) Подавление диалоговых окон (вставляется в начало кода) Suppressing dialog boxes (is inserted at the beginning of the code)

meccalte DSR manual RUS (на русском языке)

Приветствую. По служебной необходимости сделал любительский перевод ТЕХНИЧЕСКОГО РУКОВОДСТВА на DSR DIGITAL REGULATOR для генераторов meccalte Manuale_DSR_RU_rev08.ru

Permalink

Cannot retrieve contributors at this time

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Rnd function (Visual Basic for Applications)

vblr6.chm1009008

vblr6.chm1009008

office

57b9e8f9-6e3e-e68b-f5a4-c9c312b74426

12/13/2018

medium

Returns a Single containing a pseudo-random number.

Syntax

Rnd [ (Number) ]

The optional Number argument is a Single or any valid numeric expression.

Return values

If Number is Rnd generates
Less than zero The same number every time, using Number as the seed.
Greater than zero The next number in the pseudo-random sequence.
Equal to zero The most recently generated number.
Not supplied The next number in the pseudo-random sequence.

Remarks

The Rnd function returns a value less than 1 but greater than or equal to zero.

The value of Number determines how Rnd generates a pseudo-random number:

  • For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the previous number as a seed for the next number in the sequence.

  • Before calling Rnd, use the Randomize statement without an argument to initialize the random-number generator with a seed based on the system timer.

To produce random integers in a given range, use this formula:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.

[!NOTE]
To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for Number does not repeat the previous sequence.

Example

This example uses the Rnd function to generate a random integer value from 1 to 6.

Dim MyValue As Integer
MyValue = Int((6 * Rnd) + 1)    ' Generate random value between 1 and 6.

See also

  • Functions (Visual Basic for Applications)

[!includeSupport and feedback]

INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Generate Random Number in Word

Generate Random Number in Word

(OP)

7 Apr 06 17:48

Hi guys, I have a customer that wants a unique random number generated in the header of a document for tracking purposes, is there any way to use VBA code to do something like that? Was thinking some way to use the date and time down to seconds to create the number so it will end up something like this MMDDYYTIME  e.g (040707063012)

Or any other Idea or method I can use to get the same goals

Thanks for the help guys

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Join Tek-Tips® Today!

Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Tek-Tips Forums:

  • Tek-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

Return to VBA Code Examples

This tutorial will demonstrate how to work with random numbers in VBA.

RND Function

The RND Function generates a number that is between 0 and 1. The syntax of the RND Function is:

Rnd([Number]) where:

  • Number (Optional) – This is optional and if <0, the function returns the same random number on each call using [Number] as the seed, if =0, the function returns the most recent random number, if >0 the function returns the next generated random number. If blank the default >0, is used.
Sub RndNum()
    MsgBox Rnd()
End Sub

Generating a Random Number in VBA

In order to generate a random number between two values, you have to use the RND Function in combination with the INT Function  (Integer Function) using the following general formula:

  • Int(lowerbound + Rnd * ( upperbound – lowerbound + 1 ) )

So, in order to generate a random number between 2 and 30, you would use the following code:

Sub GeneratingARandomNumber()

Dim randomNumber As Integer

randomNumber = Int(2 + Rnd * (30 - 2 + 1))
Debug.Print randomNumber

End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

vba-free-addin

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)

Free Download

Уважаемый я наверное полез в космос, но постараюсь объяснить. Если на пример в определенное число, день недели и время генератор случайных чисел вывел при розыгрыше группу из семи цифр, можно ли тоже самое предугадать заранее. Я думаю что это из области той же фантастики, так как неизвестна система, мощность и программа генератора, тем боллее что им комбинция разыгоываемых чисел известна заранее, так как комбинация разыгрываемых цыфр автоматизорована и входит в единую базу данных, то они просто не пустят выгрышную комбинауию как в фильме «Оушен и его 11 друзей»

Добавлено через 1 минуту

Цитата
Сообщение от Alex77755
Посмотреть сообщение

У меня индекс цвета определяется самим числом по формуле
Если нужно задать конкретно и нет возможности задать формулой, то надо создавать массив соответствия число-цвет

Добавлено через 51 секунду
И опять же цвет цифр ли цвет числа?

Цитата
Сообщение от Alex77755
Посмотреть сообщение

И опять же цвет цифр ли цвет числа?

цвет цыфр, определенным цифрам определенный цвет

Добавлено через 2 минуты

Цитата
Сообщение от zurab_qoiava
Посмотреть сообщение

У меня индекс цвета определяется самим числом по формуле
Если нужно задать конкретно и нет возможности задать формулой, то надо создавать массив соответствия число-цвет

а вот с массивами у меня полная неразбериха.

Добавлено через 28 минут
цвета цифр нужны в таком раскладе: Rnd (0-36) красные: 1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36; зеленая: 0 (нуль), а остальные: 2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35. А в Rnd (1-36) красные: 1, 2, 9, 10, 12, 13, 20, 23, 24, 34, 35; синие: 3, 4, 14, 15, 25, 26, 36; желтые: 5, 6, 16, 17, 27, 28, 31; зеленые: 7, 8, 11, 18, 19, 21, 22, 29, 30, 32, 33; Если можно господин Alex77755 такую комбинацию написать буду очень рад и благодарен. Спишу закончить писмо. «Мужики» проснулись и пора включать «Машу и Мишу». Огромное спасибо!



0



To generate random numbers, use the Randomize statement and the Rnd function.

Random number generation is used in programming across a variety of fields in a variety of applications. Some applications of random number generation are monte carlo simulations, cryptography, testing sorting algorithms, generating sample data, adding unpredictability to games, or to fairly select an individual from a group.

It is not currently possible to generate «truly random» numbers using a computer because any algorithm used to generate an outcome would be deterministic. It is arguable that there may be no such thing as «true randomness» and the entire universe may be deterministic, but for now this is a matter of philosophical debate (see Determinism). Notwithstanding, in the current paradigm of human perception it is possible to achieve a «practical randomness» by generating outcomes that are not easily predictable. An example of practical randomness might be a coin toss. The outcome of a coin toss may be determined before the coin has come to rest, but it is ostensibly beyond the capabilities of naked human perception to predict the outcome to the level of absolute certainty. Algorithms can be used to generate pseudo-random outcomes which are similarly difficult to predict under practical circumstances, although perhaps not as random as a coin toss due to the sheer complexity of the physical universe. Some algorithms are better at generating pseudo-random outcomes than others. VBA’s pseudo-random number generator is not the best and it may be wise to use a better one for certain applications such as monte carlo simulations.

Randomize Statement

The Randomize statement is used to set the seed value for VBA’s pseudo-random number generator. Randomize can take a numeric argument as a seed. If a seed value is not provided, Randomize will use the result of the Timer function as the seed. The Rnd function may not generate sufficiently random numbers on its own. Randomize improves the results of Rnd and should be used every time before Rnd is called.

Rnd Function

The Rnd function returns a number greater than or equal to 0 and less than 1 from a sequence of pseudo-random numbers.

When Rnd is first called after starting the application it will always return the same sequence of numbers unless Randomize is used. Using Randomize with a specific number will alter the sequence in a predictable way. Using Randomize with no argument uses the result of the Timer function as the seed value and makes the Rnd function less predictable. Restarting the application will restart the sequence.

Passing the Rnd function a number less than 0 will return the same number every time.

Passing the Rnd function 0 will return the previous number returned by the Rnd function.

Passing the Rnd function a number greater than 0 or not passing any number will return the next number in the pseudo-random number generator’s sequence.

Using Rnd and Randomize

Generate Random Numbers Within a Range

To generate a random number between two bounds:

Public Function RandomLong(MinValue As Long, MaxValue As Long) As Long
    If MinValue > MaxValue Then Err.Raise 5
    Randomize
    RandomLong = Int((MaxValue - MinValue + 1) * Rnd + MinValue)
End Function

Public Function RandomDouble(MinValue As Double, MaxValue As Double) As Double
    If MinValue > MaxValue Then Err.Raise 5
    Randomize
    RandomDouble = (MaxValue - MinValue) * Rnd + MinValue
End Function

Repeat Sequence

To repeat a sequence call Rnd with a negative number before using Randomize with a specific number. Each subsequent call to Rnd will return the same numbers from the sequence.

Public Sub RepeatSequence()

    'Call Rnd with negative value
    Debug.Print Rnd(-1) '0.224007

    'Call Randomize with specific number
    Randomize 1

    'Sequence will always be the same
    Debug.Print Rnd '0.3335753
    Debug.Print Rnd '6.816387E-02
    Debug.Print Rnd '0.5938293
    Debug.Print Rnd '0.7660395
    Debug.Print Rnd '0.1892894

End Sub

Понравилась статья? Поделить с друзьями:
  • Vba word символ пробела
  • Vba word символ переноса строки
  • Vba word свойства tables
  • Vba word размеры таблицы
  • Vba word размер шрифта