我对VBA来说还不够新鲜。
我试图用VBA随机化一个列表。该列表有两个标题" Name"和"拨打"。我想尝试使用宏随机化列表,然后使用按钮应用它。我尝试过使用下面的代码但它随机化了名称和数字,但没有将它们保持在一起。含义如果我的名字是乔恩并且我有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 :(得分:3)
像@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