|
本帖最后由 duquancai 于 2018-5-31 00:26 编辑
Sub main()
Dim Data, rst$(), male$, female$, M&, F&, i&, a$(), b$(), x&, y&
Data = [B2:C101] '初始化数据
male = "男": female = "女"
M = 30: F = 20 '初始化抽取"男女"数量
For i = 1 To UBound(Data)
If Data(i, 2) = male Then
x = x + 1: ReDim Preserve a(1 To x)
a(x) = Data(i, 1)
Else
y = y + 1: ReDim Preserve b(1 To y)
b(y) = Data(i, 1)
End If
Next
If M > x Or F > y Then Exit Sub '如果抽取数量大于样本数量,那么退出程序!
ReDim rst(1 To IIf(M > F, M, F), 1 To 2)
Call extract(a, rst, male, M, 1)
Call extract(b, rst, female, F, 2)
Range("D2").Resize(UBound(rst), 2) = rst
End Sub
Sub extract(p, q, ByVal MF, ByVal num&, ByVal x&)
Dim n&, d As Object, k
Set d = CreateObject("Scripting.Dictionary")
Do While d.Count < num
n = Int(Rnd * UBound(p)) + 1
d(p(n)) = vbNullString
Loop
k = d.keys
For n = 1 To num
q(n, x) = k(n - 1)
Next
End Sub
|
|