基于另一列对列中的唯一值进行计数(Microsoft Excel 2013)

ef1yzkbh  于 2023-01-03  发布在  其他
关注(0)|答案(2)|浏览(156)

对于一个项目,我正在创建一个Excel宏,以便根据另一列值计算唯一列值。下面是我尝试创建的宏的基本示例:

数据

| 列_1|第二栏|
| - ------| - ------|
| 项目a| x|
| 项目a| Y型|
| b.人口基金|z|
| b.人口基金|z|

Sub Main()
    Dim Param As String
    Param = "a"
    MsgBox UniqueValues(Param)
End Sub

Function UniqueValues(Param As String) As String
    Dim EvaluateString As String
    EvaluateString = "=SUM(--(LEN(UNIQUE(FILTER(B:B,A:A=" & """" & Param & """" & ","""")))>0))"
    UniqueValues = Evaluate(EvaluateString)
End Function

期望
期望对于Param = "a",函数返回2,对于Param = "b",函数返回1

问题

尽管函数在Excel for Microsoft 365 Apps for Enterprise中运行良好,但该项目要求我使用Excel for Microsoft Office Standard 2013。此版本不支持在EvaluateString中使用UNIQUEFILTER函数。
我想了解是否有一种简单的方法可以根据Excel for Microsoft Office Standard 2013中一列中的值计算另一列中的唯一值。非常感谢您的帮助。

9avjhtql

9avjhtql1#

您可以使用数组公式
第一个月
输入公式后,您需要按Ctl + Shift + Enter,而不是Enter

在VBA中,可按如下所示使用上述公式

Option Explicit

Sub Main()
    Dim Param As String
    Param = "b"
    
    MsgBox "The count for " & Param & " is " & UniqueValues(Param)
End Sub

Function UniqueValues(Param As String) As String
    Dim EvaluateString As String
    Dim ws As Worksheet
    Dim wsName As String
    
    '~~> Change this to the relevant worksheet
    Set ws = Sheet1
    wsName = "'" & ws.Name & "'!"
    
    'SUM(IF(Sheet1!A1:A5="a",1/COUNTIFS(Sheet1!A1:A5,"a",Sheet1!B1:B5,Sheet1!B1:B5)),0)
    EvaluateString = "SUM(IF(" & wsName & "$A$1:$A$5=" & _
                     Chr(34) & Param & Chr(34) & _
                     ",1/COUNTIFS(" & wsName & "$A$1:$A$5," & _
                     Chr(34) & Param & Chr(34) & _
                     "," & wsName & "$B$1:$B$5," & _
                     wsName & "$B$1:$B$5)),0)"
                     
    UniqueValues = Evaluate(EvaluateString)
End Function

行动中

qxgroojn

qxgroojn2#

当数据位于“Sheet1”中的A列和B列(从第1行开始)时,可以使用此宏(结果显示在D列和E列):

Sub macro1()
Dim a As Integer, p As Integer, x As Integer, y As Integer
a = 0: p = 0: x = 1: y = 1
With Sheets("Sheet1")
.Columns("d:e").ClearContents
Do Until x > .Cells(.Rows.Count, 1).End(xlUp).Row
a = 1
Do While .Cells(x, 1) = .Cells(y, 1)
If .Cells(x, 2) <> .Cells(y, 2) Then a = a + 1
x = x + 1
Loop
p = p + 1
.Cells(p, 4) = .Cells(y, 1)
.Cells(p, 5) = a
y = x
Loop
End With
End Sub

相关问题