【问题标题】:Randomize List VBA随机列表 VBA
【发布时间】:2017-10-11 09:31:39
【问题描述】:

我对 VBA 还很陌生。

我正在尝试使用 VBA 随机化一个列表。该列表有两个标题“名称”和“拨号”。我想尝试使用宏随机化列表,然后使用按钮应用它。我尝试过使用下面的代码,但它会随机化名称和数字,但不会将它们放在一起。意思是如果我的名字是乔恩并且我有 3 个表盘,它会将我的表盘移动到其他地方。任何帮助将不胜感激。

谢谢,

Sub Random()
        Dim tempString As String
        Dim tempInteger As Integer
        Dim i As Integer
        Dim j As Integer

        For i = 1 To 5
          Cells(i, 2).Value = WorksheetFunction.RandBetween(0, 1000)
        Next i

    For i = 1 To 5
        For j = i + 1 To 5

      If Cells(j, 2).Value < Cells(i, 2).Value Then

        tempString = Cells(i, 2).Value
        Cells(i, 2).Value = Cells(j, 2).Value
        Cells(j, 2).Value = tempString
        tempInteger = Cells(i, 2).Value
        Cells(i, 2).Value = Cells(j, 2).Value
        Cells(j, 2).Value = tempInteger

      End If

        Next j
    Next i
End Sub

【问题讨论】:

  • 在代码的随机部分之前调用Randomize
  • 另外,如果你有'a'列表,你怎么有两个标题?查看数据会有所帮助。
  • 向列表中添加另一列并用随机值填充该列。然后使用该列对列表进行排序。
  • 您使用了this Tutorial,仅用于一列。跟 jsotola 说的差不多。

标签: vba excel random


【解决方案1】:

就像@jsotola 所说,排序似乎是最简单的方法:

Sub Randomer()
Dim i As Long, startRow As Long, endRow As Long
Dim ws As Worksheet

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Set ws = ActiveSheet

startRow = 2
endRow = WorksheetFunction.Max( _
    ws.Cells(ws.Rows.Count, 1).End(xlUp).Row, _
    ws.Cells(ws.Rows.Count, 2).End(xlUp).Row)

For i = startRow To endRow
    Randomize
    ws.Cells(i, 3).Value = WorksheetFunction.RandBetween(1, 1000)
Next i

ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add Key:=Range("C" & startRow & ":C" & endRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

With ws.Sort
    .SetRange Range("A" & startRow & ":C" & endRow)
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

ws.Range(ws.Cells(startRow, 3), ws.Cells(endRow, 3)).ClearContents

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub

【讨论】:

  • 有没有办法让它循环起来,只要行有数据就一直检查?
  • 我编辑了我的答案,以便它会在有数据的行中运行循环(请参阅endRow = ...),这就是您要找的吗?
  • 好的,谢谢。我试图自己做循环,但无法完全理解它。
  • 如果此答案对您有用,请考虑“接受”它,以便遇到相同问题的其他用户可以更轻松地找到答案:请参阅 stackoverflow.com/help/accepted-answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 2020-05-02
  • 2016-03-01
  • 2011-12-06
  • 1970-01-01
  • 2012-03-11
相关资源
最近更新 更多