我遇到了需要完成的VBA excel宏的问题。
我知道=RAND()
可以解决这个问题,但这是我希望能够在需要时自动调用的方式
示例表:
1 798 tea ...
2 889 coffee ...
3 990 mocca ...
4 282 latte ...
...
我希望这些行像这样改组: 示例表:
1 282 latte ...
2 798 tea ...
3 889 coffee ...
4 990 mocca ...
...
这对大多数人来说可能是一个微不足道的问题,但我是VBA的新手。
这是我尝试过的,但我每次只能明确键入范围,我不想这样做。
Sub Shuffle()
Dim list As Variant
Dim rng As Range
Dim t As Long, j As Long, k As Long
t = 100
'The line below seems to be the problem, I don't know how to reference the range values?
Set rng = Range(Cells(1, 1), Cells(1, 1).End(xlDown))
list = rng.Value
t = UBound(list, 1)
j = t
Randomize
For i = 1 To t
k = Rnd() * j + 1
lngTemp = list(j, 1)
list(j, 1) = list(k, 1)
list(k, 1) = lngTemp
j = j - 1
Next
rng.Value = list
End Sub
非常感谢任何帮助。
答案 0 :(得分:1)
如果您想学习如何在标准VBA中执行此操作,我们当然可以提供帮助。但是,更快的解决方案 - 可以在Excel外部运行 - 是使用PowerShell
随机排序csv
文件 C:\ temp \ test.csv 并写入新文件 C:\ temp \ test2.csv 你能
Sub Better()
X = Shell("powershell.exe $users = gc C:\temp\test.csv ;Get-Random -InputObject $users -Count $users.Count | out-file C:\temp\test2.csv -Encoding ascii", 1)
End Sub
$users = gc C:\temp\test.csv
Get-Random -InputObject $users -Count $users.Count | out-file C:\temp\test2.csv -Encoding ascii
答案 1 :(得分:1)
=RAND
Sort
并删除工作列我认为比在数组中交换整行更清晰
码
Sub Shuffle()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Set rng1 = Cells.Find("*", [a1], xlValues, , xlByRows, xlPrevious)
Set rng2 = Cells.Find("*", [a1], xlValues, , xlByColumns, xlPrevious)
Set rng3 = Range([a1], Cells(rng1.Row, rng2.Column + 1))
With rng3
.Columns(rng3.Columns.Count).FormulaR1C1 = "=RAND()"
'not strictly needed but shows the sort order before a recalc
.Columns(rng3.Columns.Count).Value = .Columns(rng3.Columns.Count).Value
.Sort Cells(1, rng3.Columns.Count), xlAscending
.Columns(rng3.Columns.Count).ClearContents
End With
End Sub