一、效果展示(以下是三次随机打乱的结果)
二、代码
Sub 随机分单词到后面的单元格()Dim C1 As CellDim str, str1, aDim shuffledArray() As VariantSet C1 = Selection.Range.Tables(1).Cell(1, 1)str = C1.Range.textstr = mid(str, 3, Len(str) - 4)str1 = Split(str, vbCr)' 获取数组大小arraySize = UBound(str1) - LBound(str1) + 1halfSize = 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 Thengroup1(i) = shuffledArray(i)Elsegroup2(i) = shuffledArray(i)End IfNext i' 输出结果For Each a In group1str2 = str2 & a & vbCrNextFor Each a In group2str3 = str3 & a & vbCrNextSelection.Range.Tables(1).Cell(1, 2).Range.text = str2Selection.Range.Tables(1).Cell(1, 3).Range.text = str3End SubSub 随机打乱数组(ByRef arr() As Variant)Dim i As IntegerDim j As IntegerDim temp As VariantDim n As Integern = UBound(arr) - LBound(arr) + 1For 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) = tempNext i
End Sub