简体   繁体   English

如何在Excel中动态计数范围?

[英]How to dynamic count range in excel?

|A|B|C|D|E|F|G|
|3|5|0|4|0|9|6|

I want to count dynamic count value and not count if value 0. 我想对动态计数值进行计数,而不是对值0进行计数。

Example. 例。

  1. count 2 time range A1-G1 Result is 5. 计算2个时间范围A1-G1结果为5。

  2. count 3 time range A1-G1 Result is 4. 计算3个时间范围A1-G1结果为4。

  3. count 4 time range A1-G1 Result is 9. 计算4个时间范围A1-G1结果为9。

how to coding in excel. 如何在Excel中编码。

You can use the INDEX function to move across a range of values: 您可以使用INDEX函数在一系列值之间移动:

=IF(INDEX(A1:G1,0,A4)=0,INDEX(A1:G1,0,A4+1),INDEX(A1:G1,0,A4))

Where A4 is the count. 其中A4是计数。 However if the result of the range is 0, it will move to the next, this will only work with a single instance of 0. So one after another would result in 0. 但是,如果范围的结果为0,它将移至下一个,这仅适用于0的单个实例。因此,一个接一个的实例将导致0。

A more full proof solution is to use VBA, here is a custom function for this: 一个更全面的解决方案是使用VBA,这是为此的自定义函数:

Public Function DynamicResult(ByVal Rng As Range, ByVal Count As Integer) As Integer

Dim i As Integer: i = 1

For Each cell In Rng

    If (i = Count) Then
        If cell > 0 Then
        DynamicResult = cell
    Else
        Count = Count + 1
    End If
End If

i = i + 1

Next cell

End Function

If you paste this code into a VBA module you can use it like so: 如果将此代码粘贴到VBA模块中,则可以这样使用:

=DynamicResult(A1:G1,7)

Starting with 1 in A2, fill this formula across from B2 onwards to number the cells:- 从A2中的1开始,从B2开始填写此公式以对单元格进行编号:

=IF(B1,A2+1,A2)

and use this formula to look up the value corresponding to the position in A4:- 并使用此公式查找与A4中的位置相对应的值:-

=IFERROR(INDEX($A1:$G1,MATCH(A4,$A2:$G2,0)),"")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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