很抱歉,我的工作笔记本电脑安全性不允许我粘贴在此处。我有一个具有多个重复值的行,例如再次包含2s,3s,1s和3s的BI列。最后一列中的值为3。我想计算最后几列是一个值3,然后才能更改为其他东西。
例如:如果行看起来像
2 2 2 3 3 3 1 1 2 2 3 3 2 2 2 2,然后我想要的答案是5,因为最后一个值是2,并且在最后5列。
我希望这是有道理的。
谢谢,Parul。
您可以通过在这样的VBA中创建一个UDF(用户定义的函数)来做到这一点:
Function CountLast(x As Range, y As Integer)
Dim lColumn, count
lColumn = x.Cells(x.count).Column 'Get last column in range x
count = 0
For i = lColumn To 0 Step -1 'Start with last column and work from right to left
If Cells(1, i).Value <> y Then 'Compare value of each cell with the value provided in y and leave the loop if not found
Exit For
End If
count = count + 1 'Counts how many times the value is found
Next i
CountLast = count 'Returns the counted value
End Function
然后您会这样使用:
=CountLast(B1:BI1,BI1)
对于您使用的问题中提供的示例数据:
=CountLast(A1:P1,P1)
,结果答案是5
正在发生的事情是,UDF正在找到范围内的最后一个单元格,然后从中开始,将其与您还提供功能和从右到左工作的选定值进行比较(step -1
)它们匹配并最终返回计数值。