vba 在excel宏中将字符串转换为long
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7630630/
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
Convert string to long in excel macro
提问by sab
How can I convert string to long in excel macro. CLng is giving me type mismatch error
如何在excel宏中将字符串转换为long。CLng 给我类型不匹配错误
Dim wStr As String
Dim w As Long
wStr = "=RAND() * 0.3 + 0.35"
w = CLng(wStr)
回答by RonnieDickson
Try the formula for w below.
试试下面的 w 公式。
w = CLng(Evaluate(wStr))
Or forget trying to use an "Excel formula", and go straight to VBA with with its random function counterpart
或者忘记尝试使用“Excel 公式”,然后直接使用其随机函数对应的 VBA
w = CLng(Rnd() * 0.3 + 0.35)
回答by chris neilsen
The root cause of your error is that CDbl
expects a numeric value or a string that lookslike a number. the string "=RAND() * 0.3 + 0.35"
itself does not look like a number, even though it will evaluateto a number.
错误的根本原因是CDbl
需要一个数值或一个看起来像数字的字符串。字符串"=RAND() * 0.3 + 0.35"
本身看起来不像一个数字,即使它会计算为一个数字。
What are you actually trying to achieve here?
你真正想在这里实现什么?
If its to get a long integer result from the formula =RAND() * 0.3 + 0.35, use
如果要从公式 =RAND() * 0.3 + 0.35 中获得长整数结果,请使用
Dim w as Long
w = Rnd() * 0.3 + 0.35
If its to emulate a cell formula use
如果它模拟单元格公式使用
Dim w as Long
w = Application.Evaluate("=RAND() * 0.3 + 0.35")
As to the formula itself, why this construct? It will return Single in the range [0.35, 0.65) which when rounded to a Long will return 0 or 1 at 50% probability of each.
Why not use
至于公式本身,为什么要这样构造?它将返回 [0.35, 0.65) 范围内的 Single,当四舍五入为 Long 时,将以 50% 的概率返回 0 或 1。
为什么不使用
w = Rnd()
or
或者
w = Application.Evaluate("=RAND()")
or
或者
w = Application.WorksheetFunction.RandBetween(0, 1)
or is there some other reason I've missed?
还是有其他原因我错过了?