在VBA中连续计算整行数字“串”的数量函数

问题描述:

我一直在争夺这一天数天,并且显然缺少一些东西。自从我上次使用VBA以来,我一直在努力记住。在VBA中连续计算整行数字“串”的数量函数

寻找一行中'1'的'游览'或不间断'串'的数量。

数据和答案,我在找的是这(在其自己的列各数字为):

0 0 1 1 1 0 1 0 1 = 3 
1 0 0 0 0 0 0 0 0 = 1 
0 0 0 0 1 1 1 1 1 = 1 

曾尝试以下功能:

Function TOURCOUNT(TourList As Range) 
Dim var As Variant 

var = TourList.Value 

For Each var In TourList 
    If var = 1 And var + 1 = 1 Then 
    TOURCOUNT = TOURCOUNT 
    ElseIf var = 1 Then 
    TOURCOUNT = TOURCOUNT + 1 
    End If 
Next 

End Function 

而刚刚通过的细胞运行:

​​

和其他一些小的变化。很明显,我并没有正确地说明一些事情。 'And'评估偏移量当我意外偏移行而不是列时,if语句返回错误的数字。但当我纠正它只是返回0.

任何帮助将不胜感激!

谢谢!

我不确定你想要做什么,但从你的例子来看,这样的事情会做的工作。

一般来说,您将范围作为参数传递,它会在行中进行,并在循环中进行两次检查。如果两项检查均成功,则lngResult将递增。

enter image description here

Option Explicit 

Public Function Uninterrupted(rngRange As Range) As Long 

    Dim rngCell   As Range 
    Dim lngResult  As Long 
    Dim blnInterruped As Boolean 

    For Each rngCell In rngRange 
     If rngCell Then 
      If Not blnInterruped Then lngResult = lngResult + 1 
      blnInterruped = True 
     Else 
      blnInterruped = False 
     End If 
    Next rngCell 

    Uninterrupted = lngResult 

End Function 
+0

谢谢,这正是我所需要的! – TessaB

+0

@TessaB - 酷! :) – Vityata

+1

由于您已经通过了检查的整个范围,因此您不需要使该功能变得不稳定。 – Rory