按大小

时间:2018-05-17 11:45:49

标签: vba excel-vba excel

我有一些特定值(金额)的动态表格范围。这些金额通过我创建的宏生成到表中。

enter image description here

我想做什么:按编号将这些金额排在空列中。 例如。 89k旁边的G列中的单元格将被排名为1,77k旁边的单元格将为2等等。

我也已经定义了其他函数,出于可读性的原因我不打算解释,但是你需要知道的是:通过函数获得两个变量

  
      
  1. tbl_first =(int)第一个表项的ListRow的索引(因此在这种情况下,它将是89k =第一行的行,因此在此示例中为1)
  2.   
  3. tbl_last =(int)与上面相同,但将本例中的最后一行(77k)索引为7
  4.   

所以我的代码是以下

' sets the tbl variable to the red table in the picture
Dim tbl As ListObject: Set tbl = Sheets("Summary").ListObjects("time_top") 

Dim pos As Integer, diff as integer
diff = tbl_last - tbl_first
For j = tbl_first To tbl_last ' loops through all the added rows
  For n = 1 to diff' indexing for the large function
     ' index the pos through the excel large function for our values (should return the k-th position from the largest value)
     pos = Application.WorksheetFunction.Large(Range(Cells(tbl_first, 6), Cells(tbl_last, 6)), n) 

     With tbl.ListRows(1)
       .Range(j, 6) = pos ' add the value to the column G to the right
     End With
 Next n
Next j

所以预期结果如下:

enter image description here

我也一直收到以下错误,这是由于我错误地分配了pos值而导致的。

enter image description here

无论哪种方式,这里可能存在多种错误,而且更优雅的解决方案就在那里,但这还没有打到我。

1 个答案:

答案 0 :(得分:0)

认为你需要排名(注意同等级别)。 Large返回集合的第n个最大值。

这是一个关于双列表的简单示例,您可以调整它。排名将添加到第二列。

enter image description here

Sub xx()

Dim tbl As ListObject: Set tbl = Sheets("Summary").ListObjects("time_top")

Dim r As Range

For Each r In tbl.ListColumns(1).DataBodyRange
    r.Offset(, 1) = WorksheetFunction.Rank(r, tbl.ListColumns(1).DataBodyRange)
Next r

End Sub