确定数组大小

时间:2014-01-06 03:26:44

标签: excel-vba vba excel

我目前面临的问题是如何在循环结束后确定数组的大小。下面是我对该特定功能的编码。

Function analyse(ByVal work_date As Date, time As String, action As String, decision As Boolean, branch As String) As String
    Dim sh As Worksheet
    Dim att_time(6) As String
    Dim dated(1) As Date
    Set sh = Worksheets("shifthr")

    lastrec = sh.Range("C" & Rows.Count).End(xlUp).Row
    a = 1
    For i = 2 To lastrec
        dated(a) = work_date
        If branch = sh.Cells(i, 1) Then
            att_time(a) = time
            a = a + 1
        End If
    Next i
    If att_time(a) = 4 Then

    ElseIf att_time(a) = 6 Then

    End If
End Function

谢谢你们帮助你们。非常感谢

2 个答案:

答案 0 :(得分:0)

也许你可以改变你的昏暗语句来将你的初始数组标注为()然后使用redim保留,因为你循环“a”来增加计数 - http://msdn.microsoft.com/en-us/library/w8k3cys2.aspx

如果要查找数组的大小,可以使用ubound(arrayname)。 http://msdn.microsoft.com/en-us/library/95b8f22f(v=vs.90).aspx

答案 1 :(得分:0)

  

我目前面临的问题是如何在循环结束后确定数组的大小。

您已在dim语句中声明了数组的大小。我想你想找到数组中的元素数量?如果是,请尝试此操作( UNTESTED )另外我想您想将dated(a) = work_date保留在IF条件下?如果没有,那么您无需使用a来填充dated(a) = work_date。此外,我认为您不需要Function,因为您没有向analyse返回任何值。使用Sub

Sub analyse(ByVal work_date As Date, time As String, _
action As String, decision As Boolean, branch As String)
    Dim sh As Worksheet
    Dim att_time() As String
    Dim dated() As Date
    Dim a As Long
    Dim boolCheck As Boolean

    Set sh = Worksheets("shifthr")

    lastrec = sh.Range("C" & sh.Rows.Count).End(xlUp).Row

    a = 1

    For i = 2 To lastrec 
        If branch = sh.Cells(i, 1) Then
            ReDim Preserve dated(a)
            ReDim Preserve att_time(a)

            dated(a) = work_date
            att_time(a) = time

            a = a + 1

            boolCheck = True
        End If
    Next i

    If boolCheck = True Then
        Debug.Print UBound(dated)
        Debug.Print UBound(att_time)

        'OR

        Debug.Print a - 1
    Else
        Debug.Print "No Matching records found"
    End If
End Sub