2017-10-10 64 views
3

我是VBA的新手。随机推荐列表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 
+0

嗨,检查你的代码的identation,如果你加入的图像,这将有助于您正在使用的数据。 – QHarr

+0

在代码的随机部分之前调用'Randomize' – Moacir

+0

[为什么第一个随机数总是相同?](https://stackoverflow.com/questions/17046713/why-is-the-first -random-number-is-always-the-same) – Moacir

回答

4

像@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 
+0

有没有什么办法可以在循环中做到这一点,以便只要行有数据就可以保持检查状态? – Dan

+0

我编辑了我的答案,以便它可以运行循环,尽可能多的行有数据(请参阅'endRow = ...'),那是你在找什么? –

+0

是的,谢谢。我试图自己做这个循环,但不能完全包围它。 – Dan