|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
参与一下。。。
- Function CalculateMean(arr As Variant) As Double
- Dim sum As Double
- Dim count As Long
- Dim i As Long
- For i = LBound(arr) To UBound(arr)
- sum = sum + arr(i)
- count = count + 1
- Next i
- CalculateMean = sum / count
- End Function
- Function CalculateStdDev(arr As Variant, mean As Double) As Double
- Dim sumSqDiff As Double
- Dim count As Long
- Dim i As Long
- For i = LBound(arr) To UBound(arr)
- sumSqDiff = sumSqDiff + (arr(i) - mean) ^ 2
- count = count + 1
- Next i
- CalculateStdDev = Sqr(sumSqDiff / count)
- End Function
- Sub SelectNumbersByMeanAndStdDev()
- r = Cells(Rows.count, 1).End(3).Row
- numbers = Application.Transpose([a2].Resize(r - 1, 1))
- targetMean = 29.1 ' 示例平均值
- targetStdDev = 1.553 ' 示例标准差
- ' 初始化数组
- ReDim selection(1 To 10)
- count = 0
- ' 计算numbers数组的平均值和标准差
- mean = CalculateMean(numbers)
- stdDev = CalculateStdDev(numbers, mean)
- ' 循环直到选择足够数量的数
- Do While count < 10
- ' 随机选择数组中的一个数
- randomIndex = Int((UBound(numbers) - LBound(numbers) + 1) * Rnd + LBound(numbers))
- ' 检查这个数是否满足条件
- If Abs(numbers(randomIndex) - targetMean) <= targetStdDev Then
- ' 如果满足条件,添加到选择数组中
- count = count + 1
- selection(count) = numbers(randomIndex)
- End If
- Loop
- ' 输出结果
- For i = 1 To 10
- Cells(i + 1, "g") = selection(i)
- Next i
- End Sub
复制代码
|
评分
-
1
查看全部评分
-
|