大家好,今日推出常用“积木”过程案例分享第317期,今日内容是随机获得给定数组元素的函数。VBA是利用Office实现个人小型办公自动化的有效手段(工具)。我推出的专辑中这些资料就是我多年经验的记录,都来源于我多年的实践经验的记录。大家要把这些代码块作为一块块的积木对待,平时要多积累,建立自己的“积木库”,用时拿来可以修正、组合。这就是我的“积木编程”的思想,代码不要自己全部的录入。这些讲解就是我推出的“积木”方案,希望大家加以利用。最近代码多是出自我的第六套教程”VBA信息获取与处理”。这是非常实用的实际问题解决方案。
=========================== ① =========================
Public Function MyRandom(Mim As Long, Mam As Long, _
NS As Long, Optional ArrayBase As Long = 1) As Variant
Dim AA() As Long
Dim BB() As Long
If Mim > Mam Then
MyRandom = Null
Exit Function
End If
If NS > (Mam - Mim + 1) Then
MyRandom = Null
Exit Function
End If
If NS <= 0 Then
MyRandom = Null
Exit Function
End If
ReDim AA(Mim To Mam)
For i = Mim To Mam
AA(i) = i
Next
ReDim BB(ArrayBase To (ArrayBase + NS - 1))
Randomize
For j = LBound(BB) To UBound(BB)
i = Int((Mam - Mim + 1) * Rnd + Mim)
BB(j) = AA(i)
Next
MyRandom = BB
End Function
=========================②========================
代码讲解:这个过程是一个函数过程,输入的过程我在刚才已经讲过了,输出是一个数组,这个数组就是我们给定的值。
① Dim AA() As Long
Dim BB() As Long
上面的代码定义了两个动态数组,其中AA()是输入的数组,BB()是最后返回的值。
② If Mim > Mam Then
MyRandom = Null
Exit Function
End If
上面的代码给出了一个条件就是最大值必须要大于最小值。
③ If Ns > (Mam - Mim + 1) Then
MyRandom = Null
Exit Function
End If
上面的代码要求返回的数组个数值不能大于给定输入数值的个数。
④ If Ns <= 0 Then
MyRandom = Null
Exit Function
End If
上面的代码要求返回的数组个数的值不能小于或者等于零。
⑤ ReDim AA(Mim To Mam)
For I = Mim To Mam
AA(I) = I
Next
上面的代码给输入数值赋值
⑥ ReDim BB(ArrayBase To (ArrayBase + Ns - 1))
Randomize
For j = LBound(BB) To UBound(BB)
I = Int((Mam - Mim + 1) * Rnd + Mim)
BB(j) = AA(I)
Next
上面的代码给出返回数组的值
⑦ MyRandom = BB
返回数组
各套教程的介绍:
第1套:VBA代码解决方案
第2套:VBA数据库解决方案
第3套:VBA数组与字典解决方案
第4套:VBA代码解决方案之视频
第5套:VBA中类的解读和利用
第6套:VBA信息获取与处理
上述教程的学习顺序:1→3→2→6→5或者4→3→2→6→5。如需要可以WeChat: VBA6337或者NZ9668
分享成果,随喜正能量