需要计算未连续购买产品的#quarters

时间:2019-05-30 14:36:59

标签: excel vba

sample record

请参考图片。

我有20个季度的客户购买趋势的收入记录。我想计算每个客户的缺口,即收入连续为0的#个季度。另外,我需要计算每个客户的最大差距。

对于此特定记录,收入存在2个缺口。 2015Q1和2016Q1的黑白,2016Q4和2017Q3的黑白。我需要一个代码/逻辑来能够分别计算这两个季度(三个季度和两个季度)的差距,然后计算这些差距的最大值​​。

我尝试使用匹配索引,但这似乎无济于事。你能帮我吗?

1 个答案:

答案 0 :(得分:0)

所以我不确定您希望如何格式化结果,但我假设它将是上面信息右边的2个单元格,其中1个代表空缺数,1个代表最大GAP。以下代码应该可以提供帮助,但是必须根据要检查的行/列的数量进行更改。

   Sub Finder()

Dim X As Integer
Dim Y As Integer
Dim GapCounter As Integer
Dim MaxCounter As Integer

'This For statement should be change according to how many rows need to be done
For c = 2 To 3

GapCounter = 0
MaxCounter = 0

'This For statement should be changed according to how many columns are being viewed.
For Y = 1 To 11

'This will check to see if the next column is a 0, if so a gap is beginning and the gap counter will increase
If Cells(c, Y).Value <> 0 And Cells(c, Y + 1).Value = 0 And IsEmpty(Cells(c, Y + 1)) = False Then GapCounter = GapCounter + 1

'This is checking value,if value is 0 need to add it to the current Gap amount
If Cells(c, Y).Value = 0 Then MaxCounter = MaxCounter + 1

'Checks to see if the next value is not a 0 and is not empty, if these are met we can conclude that's all the gap that needs to be counted and compare to the previous Max gap #, if it's larger than we replace
'Then we have to reset the max counter
If Cells(c, Y + 1).Value <> 0 And IsEmpty(Cells(c, Y + 1)) = False And MaxCounter > Cells(c, 14).Value Then
'This is the cell where the max time a gap has lasted will appear.
Cells(c, 14).Value = MaxCounter
MaxCounter = 0
End If

Next
'This is the cell where the # of gaps will appear
Cells(c, 13).Value = GapCounter

Next

End Sub