随机播放csv文件行

我遇到了需要完成的VBA excelmacros的问题。

  • 我有n列和行(这些数额将永远是不同的,取决于我想要处理的.csv文件),
  • 我希望能够使用VBAmacros来随机化行

我知道=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的新手。

这是我所尝试过的,但我仅限于每次都明确input范围,我不想这样做。

 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 

任何帮助将不胜感激。

  • 您可以使用从A1返回到最后一个使用的单元格的真实使用范围
  • 添加=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 

如果你想学习如何在标准的VBA中做到这一点,我们当然可以提供帮助。 尽pipe一个更快的解决scheme – 可以从Excel外部运行 – 是使用PowerShell

要随机sorting一个csv文件C:\ temp \ test.csv并写入一个新的文件C:\ temp \ test2.csv你可以

VBA

  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 

电源shell

 $users = gc C:\temp\test.csv Get-Random -InputObject $users -Count $users.Count | out-file C:\temp\test2.csv -Encoding ascii