请帮助我,我想要做的是用数字0和2填充N2:N1041的单元格。我希望在N列中总共有100个单元格(要填充的随机单元格)以填充“0”剩下的940个细胞有“2”。或者换句话说,我希望范围的9.6%(N2:N1041)用“0”填充,其余用“2”填充。
提前非常感谢你。
答案 0 :(得分:2)
你所拥有的是一个控制Do
循环的相当简单的练习。
首先,在此范围内将所有单元格值设置为“2”。
然后,使用RandBetween
函数,选择该范围内的随机单元格以设置为“0”值。添加一个检查以确保不用0覆盖0,然后添加一个计数器,以便控制何时退出循环。
Sub TestMacro()
Dim rng As Range
Dim count0 As Integer
Dim randCell As Range
Set rng = Range("A2:A1041")
rng.Value = "2" 'Set all cells = 2.'
Do
Set randCell = rng.Cells(Application.WorksheetFunction.RandBetween(1, 1040))
'make sure we're not overwriting another 0-value'
If Not randCell.Value = 0 Then
randCell.Value = 0
'increment the counter variable'
count0 = Application.WorksheetFunction.CountIf(rng, "0")
End If
Loop While count0 < 100 'exit the loop once 100 cells have been changed to 0.'
End Sub