在Excelmacros中将string转换为long
如何在excelmacros中将string转换为long CLng给我types不匹配错误
Dim wStr As String Dim w As Long wStr = "=RAND() * 0.3 + 0.35" w = CLng(wStr)
错误的根本原因是CDbl
需要一个数字值或一个看起来像一个数字的string。 string"=RAND() * 0.3 + 0.35"
本身看起来不像一个数字,尽pipe它会计算一个数字。
你究竟想在这里做什么?
如果它从公式= RAND()* 0.3 + 0.35得到一个长整数的结果,使用
Dim w as Long w = Rnd() * 0.3 + 0.35
如果它模仿一个单元格公式使用
Dim w as Long w = Application.Evaluate("=RAND() * 0.3 + 0.35")
至于公式本身,为什么这个构造呢? 它会返回范围在[0.35,0.65]范围内的单身,当四舍五入到一个龙将返回0或1,每个概率为50%。
为什么不使用
w = Rnd()
要么
w = Application.Evaluate("=RAND()")
要么
w = Application.WorksheetFunction.RandBetween(0, 1)
还是有其他原因我错过了?
尝试下面的w公式。
w = CLng(Evaluate(wStr))
或者忘记尝试使用“Excel公式”,并使用随机函数对应直接进入VBA
w = CLng(Rnd() * 0.3 + 0.35)