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

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

二、代码

vbscript 复制代码
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
相关推荐
一川风絮千片雪6 小时前
【排版教程】如何在Word/WPS中优雅的插入参考文献
word·wps
杜大哥6 小时前
如何在WPS打开的word、excel文件中,使用AI?
人工智能·word·excel·wps
青涩小鱼8 小时前
在WPS中设置word的页码不从第一页开始,从指定页开始插入页码
word·wps
企鹅侠客1 天前
开源免费文档翻译工具 可支持pdf、word、excel、ppt
人工智能·pdf·word·excel·自动翻译
hello_simon2 天前
【Word转PDF】在线Doc/Docx转换为PDF格式 免费在线转换 功能强大好用
职场和发展·pdf·word·学习方法·word转pdf·石墨文档·word转换
有限无限资料库2 天前
VBA脚本将DeepSeek嵌入Word中教程
开发语言·c#·word
嘿嘿潶黑黑3 天前
python 快速实现链接转 word 文档
python·word
hello_simon4 天前
pdf转换成word在线 简单好用 支持批量转换 效率高 100%还原
性能优化·pdf·产品运营·word·pdf转换·自媒体·pdf转word
bu_shuo4 天前
Word中样式的管理
word·样式复制
猿大师办公助手4 天前
Weboffice在线Word权限控制:限制编辑,只读、修订、禁止复制等
vue.js·chrome·microsoft·word