功能可以在VBA中编辑的全局数组

时间:2016-10-19 14:08:34

标签: arrays excel vba excel-vba

我正在使用Excel VBA,并尝试使用全局数组来跟踪不同的计数。不同的子函数和函数能够访问全局数组array_count,但我的目标是让函数Chart编辑数组中的值。现在,函数对数组的编辑不会转移到其他子目录。

' Initialize variables
Private counter As Integer
Private Account As String

Public array_count As Variant

' Iterate over rows, reading Account
Sub RowInsert()

    array_count = Array(-1, -1, -1)

    Debug.Print array_count(0)
    Debug.Print array_count(1)
    Debug.Print array_count(2)

    For counter = 0 To 1

    Account = Worksheets("Journal").Cells(counter + 2, 2)

    Call Record(Account)

    Next counter

    End Sub

    ' Record the transaction in proper T-account 
Sub Record(Account As String)

        Dim target_row As Long

        With Worksheets("Ledger").Range("a1:c20")

            Set Header = .Find(Account)

                Debug.Print Account

            If Header Is Nothing Then

                Debug.Print "Not found."

            End If

            Dim n As Integer
            n = Chart(Account)

            Debug.Print n

            target_row = Header.row + 2 + array_count(n)

            Debug.Print target_row

            Rows(target_row).Insert Shift:=xlDown

            Cells(target_row - 1, 1) = Worksheets("Journal").Cells(counter + 2, 1).Value

                Debug.Print counter

            If IsEmpty(Worksheets("Journal").Cells(counter + 2, 3)) Then

                Cells(target_row - 1, 3) = Worksheets("Journal").Cells(counter + 2, 4).Value

            Else

                Cells(target_row - 1, 2) = Worksheets("Journal").Cells(counter + 2, 3).Value

            End If

        End With

    End Sub

    ' Count the number of entries in each T-account
    Function Chart(Account As String) As Integer

    If Account = "Cash" Then

        array_count(0) = array_count(0) + 1
        Chart = array_count(0)


    ElseIf Account = "Equipment" Then

        array_count(1) = array_count(1) + 1
        Chart = array_count(1)

        Debug.Print array_count(1)


    End If

    End Function

1 个答案:

答案 0 :(得分:0)

如果我没有意识到,你的问题是每当你运行RowInsert()时,你总是得到相同的array_count(0)值(我想,这就是你在那里有debug.prints的原因。)

原因在于:

array_count = Array(-1, -1, -1)

每次重新启动数组(使其看起来像-1,-1,-1)。我是对的吗?