Excel宏 - 计算连续父列表中的连续子列表

时间:2011-03-24 16:29:12

标签: excel vba worksheet-function

请帮我计算连续父母列表中的连续子列表 我有一个数据表:
    -----< - 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 ---- bb

如果我计算列表A中的列表B,则返回结果为4.
如果我计算列表A中的列表C,则返回结果为2.
谢谢你的帮助。

1 个答案:

答案 0 :(得分: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