我是VBA的新手,但是我想创建一个VBA脚本,它可以运行一个计算,直到答案没有小数为止。(注:不过,四舍五入不是我所追求的)
例如:我想生成3位数,它可以除以一个恒数,17。但是,我不知道这些组合。因此,我编写了单元格A1到C1的脚本,随机函数在0-9之间.
如果我希望单元格A3中的计算一直运行到A1:C1中的数字的组合,它可以完全除以常量17;这没有小数。(例如170 / 17 = 10,没有小数)。因此,单元格A1到C1中显示的值为1,7,0;这就是答案)
是否可以创建一个VBA脚本来执行此操作?
谢谢。
发布于 2016-06-22 14:52:44
考虑:
Sub dural()
With Application.WorksheetFunction
Do
Range("A1").Value = .RandBetween(1, 100)
Range("B1").Value = .RandBetween(1, 100)
Range("C1").Value = .RandBetween(1, 100)
If Range("A3").Value Mod 17 = 0 Then Exit Sub
Loop
End With
End Sub这假定单元格A3包含:
=SUM(A1:C1)而不是你的公式。

EDIT#1:
如果您希望在A1中通过C1只使用个位数,那么将此公式放入A3中。
=A1*100+B1*10+C1并使用此宏:
Sub dural2()
With Application.WorksheetFunction
Do
Range("A1").Value = .RandBetween(1, 9)
Range("B1").Value = .RandBetween(0, 9)
Range("C1").Value = .RandBetween(0, 9)
If Range("A3").Value Mod 17 = 0 Then Exit Sub
Loop
End With
End Sub发布于 2016-06-22 14:59:49
运行这个宏
Sub Macro()
Do Until Range("A3") = 17
Range("C1").Value = Int((100 - 0 + 1) * Rnd + 0)
Range("B1").Value = Int((100 - 0 + 1) * Rnd + 0)
Range("A1").Value = Int((100 - 0 + 1) * Rnd + 0)
Range("A3") = (Range("A1") + Range("B1") + Range("C1")) / 17
Loop
End Sub发布于 2016-06-22 15:46:15
从@aucuparia的注释中,您可以在范围内选择一个随机整数,结果是一个三位数乘以17,乘以它,得到一个可以被17整除的“随机”三位数。
此代码接受一个除数(在您的示例中为17,但它可以是整数)。它确定的最小数,当乘以除数得到一个三位数(lLower),并做同样的最大数。然后在这两个数字之间选择一个随机整数,乘以17,然后返回乘积。
Function RandomDivisible(ByVal lDivisor As Long) As Double
Dim lLower As Long, lUpper As Long
Dim i As Long
lLower = Round(100 / lDivisor + 0.4999, 0)
lUpper = Round(1000 / lDivisor - 0.4999, 0)
RandomDivisible = Int((lUpper - lLower + 1) * Rnd + lLower) * lDivisor
End Function用作
=RandomDivisible(17)https://stackoverflow.com/questions/37971186
复制相似问题