VBA用0和1随机填充单元格

时间:2019-03-04 22:36:56

标签: excel vba

所以我必须制作一个VBA,在其中我必须将0和1随机化。 我制作了一个非常基本的版本,仅用1s填充单元格

Sub numberchangenormal()

Dim targetrange As Range
    Dim Cell As Range

Set targetrange = Range("A1:D1")

For Each Cell In targetrange
 Cell.Value = Int(1)
Next Cell


Set targetrange = Range("F1:I1")

For Each Cell In targetrange
 Cell.Value = Int(1)
Next Cell

End Sub

在前四行(A1:D1)中,我只需要一个1(其余为0)示例:

| 0 | 0 | 1 | 0 |

在后四行(F1:I1)中,我至少需要一个1(其余为0或1)示例:

| 1 | 0 | 1 | 1 |

2 个答案:

答案 0 :(得分:1)

如果在A:D中仅需要一个 1 ,则找到一个随机数并将其填写。

redim arr(1 to 4) as long

arr(application.randbetween(1, 4)) = 1

range("A1:D1") = arr

如果必须至少有一个 1 ,但可能更多,则随机化并检查至少一个数组元素是否为 1 。如果不是,请使用上述方法确保至少一个 1

redim arr(1 to 4) as long

arr(1) = application.randbetween(0, 1)
arr(2) = application.randbetween(0, 1)
arr(3) = application.randbetween(0, 1)
arr(4) = application.randbetween(0, 1)

if (arr(1) + arr(2) + arr(3) + arr(4)) = 0 then
    arr(application.randbetween(1, 4)) = 1
end if

range("F1:I1") = arr

答案 1 :(得分:0)

所有单元都可以一次分配:

Sub numberchangenormal()
    [a1:d1,f1:i1] = "=RANDBETWEEN(0,1)"     ' set Excel formula to all of the cells
    [a1:d1] = [a1:d1].Value                 ' optional to convert the formulas to values
    [f1:i1] = [f1:i1].Value
End Sub