用VBA在Word中随机打乱单词表,进行分列

一、效果展示(以下是三次随机打乱的结果)

 

二、代码

Sub 随机分单词到后面的单元格()
    Dim C1 As Cell
    Dim str, str1, a
    Dim shuffledArray() As Variant
    Set C1 = Selection.Range.Tables(1).Cell(1, 1)
    str = C1.Range.text
    str = mid(str, 3, Len(str) - 4)
    str1 = Split(str, vbCr)
    
        ' 获取数组大小
    arraySize = UBound(str1) - LBound(str1) + 1
    halfSize = arraySize \ 2
    
    ' 生成一个打乱的数组
    ReDim shuffledArray(LBound(str1) To UBound(str1))
    For i = LBound(str1) To UBound(str1)
        shuffledArray(i) = str1(i)
    Next i
    
    ' 打乱数组
    Call 随机打乱数组(shuffledArray)
    
    ' 分配到两个新数组
    ReDim group1(LBound(shuffledArray) To halfSize - 1)
    ReDim group2(halfSize To UBound(shuffledArray))
    
    For i = LBound(shuffledArray) To UBound(shuffledArray)
        If i < halfSize Then
            group1(i) = shuffledArray(i)
        Else
            group2(i) = shuffledArray(i)
        End If
    Next i
    
    ' 输出结果
    For Each a In group1
        str2 = str2 & a & vbCr
    Next
    For Each a In group2
        str3 = str3 & a & vbCr
    Next
    Selection.Range.Tables(1).Cell(1, 2).Range.text = str2
    Selection.Range.Tables(1).Cell(1, 3).Range.text = str3

End Sub

Sub 随机打乱数组(ByRef arr() As Variant)
    Dim i As Integer
    Dim j As Integer
    Dim temp As Variant
    Dim n As Integer
    
    n = UBound(arr) - LBound(arr) + 1
    
    For i = LBound(arr) To UBound(arr)
        j = Int((UBound(arr) - LBound(arr) + 1) * Rnd + LBound(arr))
        temp = arr(i)
        arr(i) = arr(j)
        arr(j) = temp
    Next i
End Sub

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值