【发布时间】:2021-06-26 11:58:06
【问题描述】:
谁能帮助解决以下问题? 如何计算 Column "A" 中的每个不同值在 Column "B" 中的值出现多少次(例如 ">30")?在完美的世界中,这将是多个标准。
在 A:B 列 - 源数据中,E:F 列是预期结果。此外,它可以在两张纸之间分开。
Source data and expected result
到目前为止,我发现的代码仅将唯一值从一张纸提取到另一张纸,并计算其在整个范围内的出现次数。
Sub UniqueIdentifiers()
Dim lastRow As Long
Dim count As Integer, i As Integer, j As Integer
lastRow = Sheets(1).Range("E" & Rows.count).End(xlUp).Row
i = 2
j = 2
Do Until i > lastRow
count = Application.WorksheetFunction.CountIf(Sheets(1).Range("C2:C" & lastRow), Sheets(1).Cells(i, 3))
For Each c In Sheets(1).Range("C" & lastRow).Cells
Sheets(2).Cells(j, 1) = Sheets(1).Cells(i, 3)
Sheets(2).Cells(j, 2) = count
j = j + 1
Next
i = i + 1
Loop
Sheets(2).Range("A:B").RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
End Sub
更新 - 问题已解决
感谢@Gary 在Excel VBA find unique values in combinations of 2 or more columns 问题中的学生回答,我已经设法找到解决我的任务的问题,如果条件刚刚添加到他的代码中。完整代码如下:
Sub uniKue()
Dim i As Long, N As Long, s As String, r As Range
N = Cells(Rows.count, "A").End(xlUp).Row
For i = 2 To N
If Cells(i, 4) >= 30 Then
Cells(i, 5) = Cells(i, 2) & " " & Cells(i, 5)
Cells(i, 6) = Cells(i, 5)
End If
Next i
Range("F:F").RemoveDuplicates Columns:=1, Header:=xlNo
For Each r In Range("F:F").SpecialCells(2).Offset(, 1)
r.Formula = "=COUNTIF(E:E," & r.Offset(, -1).Address & ")"
Next r
End Sub
感谢大家的贡献。
【问题讨论】:
-
只使用
COUNTIFS有什么问题? -
这将是另一个宏的一部分,我宁愿在 vba 中这样做,以避免每次都写公式
-
您可以使用 VBA 编写公式。