我在使用 VBA Excel 时遇到了问题。
在 F 列中,我有一个数字 57.07%。此列有 102 行。我们的想法是生成百分比的随机值,但这些随机数的总平均值必须是 57.07%
我设法生成了随机全数。但由于某种原因,添加和删除小数时我没有得到任何结果。
Sub RandomiseSum()
Dim countries As Range, country As Range, pageviews As Range, clicks As Range, impressions As Range, col_f As Range, col_g As Range, col_h As Range, earnings As Range
Dim arr() As Double, i, z, y As Integer
'~~>Count the result of the range of countries
Set countries = Range("B4:B102")
Set pageviews = Range("C4:C102")
Set impressions = Range("D4:D102")
Set clicks = Range("E4:E102")
Set col_f = Range("F4:F102")
Set col_g = Range("G4:G102")
Set col_h = Range("H4:H102")
Set earnings = Range("I4:I102")
ReDim arr(countries.count - 1)
For i = 0 To countries.count - 1
arr(i) = Rnd
Next i
i = i - 1 '~~> Remove 1 from the total cell number in order to put the decimals/diferences in it at the end
'~~> Totals
TotalC = Range("C2").Value
TotalD = Range("D2").Value
TotalE = Range("E2").Value
avg_f = Range("F2").Value
avg_g = Range("G2").Value
avg_h = Range("H2").Value
TotalI = Range("I2").Value
col_h = avg_h
half1 = i / 2
half2 = (i / 2) + 1
z = half2
y = 4
x = 0
Do Until x = half1
this_nr = "H" & y
xnum = WorksheetFunction.RandBetween(0, 42) / 100
Range(this_nr).Value = Range(this_nr).Value - xnum
y = y + 1
z_nr = "H" & z
Range(z_nr).Value = Range(z_nr).Value + xnum
z = z + 1
x = x + 1
Loop
rnr = 0
Do Until rnr = half1
x12 = WorksheetFunction.RandBetween(4, 102)
x22 = WorksheetFunction.RandBetween(4, 102)
x12 = "H" & x12
x22 = "H" & x22
x3 = x12
Range(x12).Value = Range(x22).Value
Range(x22).Value = Range(x3).Value
rnr = rnr + 1
Loop
y = 4
z = half2
For x = 0 To x = half1
this_nr = "H" & y
z_nr = "H" & z
Range(this_nr).Value = Range(this_nr).Value - 0.3
Range(z_nr).Value = Range(z_nr).Value + 0.03
z = z + 1
x = x + 1
Next x
End Sub
从图片中您可以看到,我在所有单元格中都得到了 .07,但我无法从某些单元格中删除该值并将其添加到其他单元格中。
有什么想法吗?
我的循环错了吗?
答案1
我设法解决了这个问题。如果其他人遇到同样的问题,这里是代码。我在这里所做的是,我添加了另一个名为“xnum2”的变量,我将在其中生成一个随机十进制数,然后对于每个循环,我将从 CELLx.value 中删除该值并将其添加到另一个 CELLy.value,这样平均值仍然相同。
col_h = avg_h
half1 = i / 2
half2 = (i / 2) + 1
z = half2
y = 4
x = 0
Do Until x = half1
this_nr = "H" & y
xnum = WorksheetFunction.RandBetween(0, 42) / 100
Range(this_nr).Value = Range(this_nr).Value - xnum
xnum2 = WorksheetFunction.RandBetween(0, 9) / 10000
Range(this_nr).Value = Range(this_nr).Value - xnum2
y = y + 1
z_nr = "H" & z
Range(z_nr).Value = Range(z_nr).Value + xnum
Range(z_nr).Value = Range(z_nr).Value + xnum2
z = z + 1
x = x + 1
Loop
rnr = 0
Do Until rnr = half1
x12 = WorksheetFunction.RandBetween(4, 102)
x22 = WorksheetFunction.RandBetween(4, 102)
x12 = "H" & x12
x22 = "H" & x22
x3 = x12
Range(x12).Value = Range(x22).Value
Range(x22).Value = Range(x3).Value
rnr = rnr + 1
Loop