需要在下一行更大/更小时添加到计数器

时间:2013-08-01 19:40:16

标签: excel vba

Sub HMM()
Dim x As Integer

Dim GG As Integer
Dim Gr As Integer
Dim rG As Integer
Dim rr As Integer

For x = 3 To x = 26126
    If ActiveSheet.Cells(x, 3) > 0 And ActiveSheet.Cells(x + 1, 3) > 0 Then
            GG = GG + 1
    End If
    If ActiveSheet.Cells(x, 3) > 0 And ActiveSheet.Cells(x + 1, 3) < 0 Then
            Gr = Gr + 1
    End If
    If ActiveSheet.Cells(x, 3) < 0 And ActiveSheet.Cells(x + 1, 3) > 0 Then
            rG = rG + 1
    End If
    If ActiveSheet.Cells(x, 3) < 0 And ActiveSheet.Cells(x + 1, 3) < 0 Then
            rr = rr + 1
    End if
 Next x

 With ActiveSheet
   .Cells(2, 30) = GG
   .Cells(3, 30) = Gr
   .Cells(4, 30) = rG
   .Cells(5, 30) = rr
End With

End Sub

所以我有一长串的数字,从C3到C26126。我需要做的是找出正数在正数(GG)之前的次数,负数在正数(rG)之前的次数等等。所以我需要GG Gr rG和rr。对不起,如果这还不够清楚。

示例:我有一个表y:[ - 1,2,2,3,-1,-2,2] GG = 2,Gr = 1,rG = 2,rr = 1

我的最终目标是为我的时间序列找到一个简单的隐马尔可夫模型。

2 个答案:

答案 0 :(得分:1)

Sub Tester()

    Dim pp, pn, np, nn, x, arr, v1, v2

    arr = ActiveSheet.Range("C3:C1110").Value
    For x = 1 To UBound(arr, 1) - 1
        v1 = arr(x, 1): v2 = arr(x + 1, 1)
        If v1 > 0 And v2 > 0 Then
            pp = pp + 1
        ElseIf v1 > 0 And v2 < 0 Then
            pn = pn + 1
        ElseIf v1 < 0 And v2 > 0 Then
            np = np + 1
        ElseIf v1 < 0 And v2 < 0 Then
            nn = nn + 1
        End If
    Next x

    Debug.Print pp, pn, np, nn

End Sub

答案 1 :(得分:0)

不太确定问题是什么......因为你已经给出了答案

Sub HMM()
    Dim myWS As Worksheet
    Set myWS = Worksheets("Sheet1")

    Dim x As Integer

    Dim GG As Integer
    Dim Gr As Integer
    Dim rG As Integer
    Dim rr As Integer

    'Initially 0 by default but it's always good to be explicit
    GG = 0
    Gr = 0
    rG = 0
    rr = 0

    'Count from 3 to 26125 instead of from 3 to 26126
    With myWS
        For x = 3 To 26125

            If .Cells(x, 3).Value > 0 Then
                If .Cells(x + 1, 3).Value > 0 Then
                    GG = GG + 1
                ElseIf .Cells(x + 1, 3).Value < 0 Then
                    Gr = Gr + 1
                End If
            ElseIf .Cells(x, 3).Value < 0 Then
                If .Cells(x + 1, 3).Value > 0 Then
                    rG = rG + 1
                ElseIf .Cells(x + 1, 3).Value < 0 Then
                    rr = rr + 1
                End If
            End If
        Next x

        Debug.Print GG, Gr, rG, rr

    End With

End Sub

如果我是你,我会将.Cells(x + 1,3)设置为变量然后进行比较..但我不确定我应该使用哪种变量类型,因为对所有内容都有限制。