2011-03-24 70 views
1

請幫助我在連續父列表中計算連續子列表。
我有一個數據表中:
----- < - A(列) - > < - B(列) - > < - C(列) - >
1 ----- AA - ------------- aa ---------------- aa
2 ----- bb ---------- ----- bb ---------------- bb
3 ----- aa ------------------ ------------------ AA
4 ----- AA
5 ----- BB
6 ----- BB
7 - ---- aa
8 ----- aa
9 ----- AA
10 ---- BB
11 ---- AA
12 ---- BBExcel宏 - 連續父列表中的連續子列表計數

如果我在列表中的計數列表B,返回的結果是4。
如果我列表A中的列表C,返回的結果是2.
感謝您的幫助。

+0

B/C類型列的深度上是否存在最大行數? – 2011-03-24 16:39:02

回答

1

這幾乎是一個蠻力的解決方案,但會訣竅。

Option Explicit 

Public Function PatternCount(PatternRange As Excel.Range, TargetRange As Excel.Range) As Integer 
    Dim oCell As Excel.Range 
    Dim oEndCell As Excel.Range 
    Dim sTargetPattern As String 
    Dim sPattern As String 
    Dim iCount As Integer 

    sTargetPattern = RangeSignature(PatternRange) 

    For Each oCell In TargetRange 
     Set oEndCell = oCell.Offset(RowOffset:=PatternRange.Count - 1) 
     sPattern = RangeSignature(Range(oCell, oEndCell)) 

     If sPattern = sTargetPattern Then iCount = iCount + 1 
    Next oCell 

    PatternCount = iCount 

    Set oCell = Nothing 
    Set oEndCell = Nothing 
End Function 

Private Function RangeSignature(TargetRange As Excel.Range) As String 
    Dim oCell As Excel.Range 
    Dim sPattern As String 

    For Each oCell In TargetRange.Cells 
     sPattern = sPattern & oCell.Value & "|" 
    Next oCell 

    RangeSignature = sPattern 

    Set oCell = Nothing 
End Function 
+0

不錯!請注意,這將計算重疊事件。因此,如果在'a | b | a | b | a | b | a | b | a | b | a | b'中查找'a | b | a | b','PatternCount'將返回5,而不是3你可能(或可能不會)期待。 – 2011-03-25 20:11:51