用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
相关推荐
YJlio12 小时前
2026年4月19日60秒读懂世界:从学位扩容到人形机器人夺冠,今天最值得关注的6个信号
python·安全·ios·机器人·word·iphone·7-zip
Digitally2 天前
如何在Windows、Mac和移动设备上永久删除Word文档
windows·macos·word
R-sz3 天前
前端直接将页面 HTML 报表导出为 Word 文档,html转word
前端·html·word
DANGAOGAO3 天前
Word宏一键交叉引用
word·交叉引用
梅羽落3 天前
word改页码
word
傻啦嘿哟4 天前
使用 Python 管理 Word 节及页面布局设置
开发语言·python·word
梦因you而美4 天前
Python批量读取Word表格(全格式兼容:上下标+公式+字体样式)
python·自动化·word·办公自动化·提取word表格·omml格式
CodeCxil4 天前
基于Vue的在线Online Word文档编辑器-效果预览
前端·vue.js·word
CodeCxil4 天前
基于Vue的在线Online Word文档编辑器
vue.js·编辑器·word
诸葛大钢铁5 天前
如何将PDF以矢量图插入Word? 在线将PDF转为SVG格式
pdf·word·矢量图·pdf2svg