vba 如何在VBA中生成随机正负数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24839742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:54:58  来源:igfitidea点击:

How to generate random positive and negative numbers in VBA

vba

提问by codea

I am trying to generate random integers over the range (-5, 5) using VBA, something like 100+/- rnd 5. I was wondering if some of you has more elegant way to do it. What I have so far is only "+"

我正在尝试使用 VBA 在 (-5, 5) 范围内生成随机整数,例如 100+/- rnd 5。我想知道你们中的一些人是否有更优雅的方法来做到这一点。到目前为止我只有“+”

randomRange= 100 + CInt(Rnd * 5)

采纳答案by codea

I have found a solution.

我找到了解决办法。

randomRange=100 + cint((Rnd()*((-1)^INT(rnd()*10))) * 5)

Where

在哪里

  • (Rnd()*((-1)^INT(rnd()*10))) * 5is the part that generates number between -1 and 1.
  • *5 gives a number between -5 and 5.
  • (Rnd()*((-1)^INT(rnd()*10))) * 5是生成 -1 和 1 之间数字的部分。
  • *5 给出一个介于 -5 和 5 之间的数字。

Thanks to DRJ on Mr. Excel Forum

感谢Excel 先生论坛上的 DRJ

回答by Doug Glancy

You can use Excel's RANDBETWEENfunction like this:

您可以RANDBETWEEN像这样使用 Excel 的函数:

randomRange= 100 + Application.WorksheetFunction.RandBetween(-5, 5)

回答by osquro

Try this

尝试这个

randomRange = 100 + CInt(5 * (2 * Math.Rnd - 1))