簡體   English   中英

對另一列中的列值進行排名

[英]Rank column values in another column

我知道這一行是錯誤的:

ws.Cells(i, "D").Resize(39).Rank_Eq(2, "2:40", 1) = ws.Cells(Rows.Count, "E").End(xlUp).Offset(1, 0)

我想在 E 列中對整個 D 列進行排名。這些數字應該“分組”為 39 個數字。

Private Sub CommandButton2_Click()
Dim lrow As Long
Dim i As Long

Dim ws As Worksheet
Set ws = ActiveWorkbook.Worksheets("Sheet1") 'Set the name of the sheet

lrow = ws.Cells(Rows.Count, "D").End(xlUp).row  'Find the last row in column D
For i = 2 To lrow Step 39 'Loop every group (group of 13 rows) in column D
    ws.Cells(i, "D").Resize(39).Rank_Eq(2, "2:40", 1) = ws.Cells(Rows.Count, "E").End(xlUp).Offset(1, 0)
Next i

End Sub

在此處輸入圖像描述

我不太了解這個主題,但是在網頁上https://docs.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.rank_eq

寫的是表達式.Rank_Eq (Arg1, Arg2, Arg3),而表達式A變量代表了一個WorksheetFunction object。 在您的代碼中,它看起來像 Range object。

我認為代碼會做你想做的事。 請注意頂部的常量,您必須根據需要設置這些常量。

  1. FirstDataRow - 您的數據似乎從第 2 行開始。所以,不要更改。
  2. GroupSize - 我測試了 3 行的組。 我認為你想要 39 行的組。 更改。
  3. TgtClm - 您的數據在第 4 列(D 列)。 現在不需要改變。

一旦你設置了這 3 個常量,代碼就可以運行了。 請試一試。

Private Sub CommandButton2_Click()
    ' 034

    Const FirstDataRow  As Long = 2
    Const GroupSize     As Long = 3             ' change to suit
    Const TgtClm        As Long = 4             ' Target Column (4 = column D)
                                                ' the output will be in the adjacent column

    Dim Ws              As Worksheet
    Dim Rng             As Range                ' cells in one group
    Dim lRow            As Long                 ' last used row
    Dim Rstart          As Long                 ' first row in group range
    Dim Rend            As Long                 ' last row in group range


    Set Ws = ActiveWorkbook.Worksheets("Sheet1")            'Set the name of the sheet
    lRow = Ws.Cells(Ws.Rows.Count, TgtClm).End(xlUp).Row    'Find the last used row

    Rstart = FirstDataRow
    Do
        Rend = Application.Min(Rstart + GroupSize - 1, lRow)
        With Ws
            Set Rng = .Range(.Cells(Rstart, TgtClm), .Cells(Rend, TgtClm))
        End With

        Rng.Offset(0, 1).Formula = "=RANK(" & Rng.Cells(1).Address(0, 1) & _
                                          "," & Rng.Address & ",0)"
        Rstart = Rend + 1
        If Rstart > lRow Then Exit Do
    Loop
End Sub

請注意,RANK 公式中的最后一個 0(此處為: & Rng.Address & ",0)" )指示按降序排列,這意味着最高的數字將獲得最低的排名(100 = 1、90 = 2 等)。 如果您需要相反的順序,請更改為1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM