只使用vba填充两个数字的单元格

请帮助我,我想要做的是填充单元格N2:N1041与数字0和2.我想总共100个单元格(填充随机单元格)在N列填充“0”和剩余940细胞有“2”。 换句话说,我希望范围的9.6%(N2:N1041)填充“0”,其余填充“2”。

非常感谢你提前。

你所拥有的是控制Do循环的一个相当简单的练习。

首先,在此范围内将所有单元格值设置为“2”。

然后,使用RandBetween函数,select该范围内的随机单元格以设置为“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