简体   繁体   中英

Excel - find a value in column A that appears less than or equal to 4 times and print in column B

I have a list of usernames sorted alphabetically in column A, with some appearing numerous times. I want to prnt the username in column B if it appears less than or equal to 4 times.

Do I need an array to go through all the different username values in the column to find the ones that appear less than or equal to 4 times?

Consider:

Sub dural()
    Dim A As Range, B As Range, v As String, K As Long
    Set A = Intersect(Range("A:A"), ActiveSheet.UsedRange)
    Set B = Range("B:B")

    K = 1

    With Application.WorksheetFunction
    For Each aa In A
        v = aa.Value
            If v <> "" Then
                If .CountIf(A, v) <= 4 Then
                    If .CountIf(B, v) = 0 Then
                        Cells(K, "B").Value = v
                        K = K + 1

                    End If
                End If
            End If
    Next aa
    End With
End Sub

在此处输入图片说明

Add a helper column and place the following formula in the second row:

=IF(AND(COUNTIF(A:A,A2)<=4,COUNTIF($A$2:A2,A2)=1),MAX($B$1:B1)+1,"")

And copy down:

在此处输入图片说明

At this point you can filter on the non Blank Cells and copy them to another range.

If you want to use a formula to get the list then Put this in another column row 2:

=IFERROR(INDEX(A:A,MATCH(ROW(1:1),B:B,0)),"")

And copy down.

在此处输入图片说明

No need for helper columns or VBA, just a bit of finely-tuned IF functions :)

=IF(COUNTIFS(BE:BE,BE2)<=4,IF(COUNTIFS($BE$1:BE2,BE2)=1,BE2,"0"),"0")

^Here, BE is where all your data is, starting on Row 2

What it does:

  1. If the Name appears 4 or fewer times,

  2. If this is the first time the Name appears in the column

  3. Print the Name
  4. (Otherwise insert 0)

To remove the 0 values ie empty rows:

  1. Paste over the formula with the same column as values (this is so you can..)
  2. .. Replace All ( Ctrl-H ) "0"s with nothing "" (so that you can..)
  3. .. Select the blank rows using Go To ( Ctrl-G ) > Special > Blanks
  4. Delete (Shift Cells Up)

You can also simply Filter out the Blank/0 values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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