gpt4 book ai didi

vba - 随机列表 VBA

转载 作者:行者123 更新时间:2023-12-02 17:36:59 25 4
gpt4 key购买 nike

我对 VBA 还很陌生。

我正在尝试使用 VBA 随机化列表。该列表有两个标题“名称”和“拨号”。我想尝试使用宏随机化列表,然后使用按钮应用它。我尝试使用下面的代码,但是它随机化了名称和数字,但没有将它们放在一起。意思是如果我的名字是 Jon 并且我有 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

最佳答案

就像 @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

关于vba - 随机列表 VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46672922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com