简体   繁体   English

使用VBA对随机表进行排序

[英]Sorting random table using VBA

I have a vba code to generate random values and then generate random values to the generated random values. 我有一个VBA代码来生成随机值,然后将随机值生成为生成的随机值。 I put these in a table and I want to sort them in ascending order, based on the random values in the first column. 我将它们放在一个表中,并希望基于第一列中的随机值以升序对其进行排序。 However, I have used several codes and tried it but I get an error everytime. 但是,我使用了几种代码并进行了尝试,但是每次都会出现错误。 Anyone knows how to solve this? 有人知道如何解决吗? My code is as follows: 我的代码如下:

Sub Button1_Click()

Range("A2:A38").Select
 ActiveSheet.Range("$A$2:$A$38").Value = "=RANDBETWEEN(1,12)"

 Range("B2:B38").Select
 ActiveSheet.Range("$B$2:$B$38").Value = "=RANDBETWEEN(1,INDEX({2,2,8,8,8,8,4,2,8,10,4,8},A2))"

Application.Calculate

Range("A2:B38").Select
 ActiveSheet.Range("$A$2:$B$38").RemoveDuplicates Columns:=Array(1, 2), Header:=xlNo



 ActiveWorkbook.Save


End Sub

You want to avoid the use of Activate and Select in your macros 您要避免在宏中使用“激活并选择”

Before doing the remove duplicates, you need to convert the result of the formulas into actual values, since sorting RANDBETWEEN formulas will only result in new random numbers: 在执行删除重复项之前,您需要将公式的结果转换为实际值,因为对RANDBETWEEN公式进行排序只会产生新的随机数:

Range("A2:A38").Formula = "=RANDBETWEEN(1,12)"

Range("B2:B38").Formula = "=RANDBETWEEN(1,INDEX({2,2,8,8,8,8,4,2,8,10,4,8},A2))"

Range("A2:B38").Value = Range("A2:B38").Value

ActiveSheet.Range("$A$2:$B$38").RemoveDuplicates Columns:=Array(1, 2), Header:=xlNo

It's also not clear to me if you want to sort the values (as mentioned in the title of your question, or remove duplicates (which is what your code does) 如果您要对值进行排序(如问题标题中所述,或删除重复项(代码所执行的操作),对我来说也不清楚

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM