如果返回或输出超出FOR循环,则EXCEL中的自定义函数不起作用

时间:2018-10-28 03:28:51

标签: excel vba excel-vba

Function DISCOUNT(quantity) ' "1-2,3,4,5-10,23" is the data in <quantity>
    Dim LString As String
    Dim LArray() As String
    Dim Daysfromto() As String
    Dim Size As Double
    Dim Days As Double
    Dim Totaldays As Double


        Totaldays = 0
        LString = quantity
        LArray = Split(LString, ",")
        Size = UBound(LArray) - LBound(LArray) + 1
                For i = 0 To Size
                        Contains = InStr(LArray(i), "-")
                        If Contains = 2 Then
                            Daysfromto = Split(LArray(i), "-")
                            Totaldays = Totaldays + Daysfromto(1) - Daysfromto(0) + 1
                        ElseIf Contains = 0 Then
                            Totaldays = Totaldays + 1
                        End If
                        MSGBOX Totaldays ' this works here
                Next i
    MSGBOX Totaldays ' this does not work here
    DISCOUNT = Totaldays ' this does not work here
End Function

1 个答案:

答案 0 :(得分:2)

LArray = Split(LString, ",")

默认情况下,这将创建一个从零开始的一维数组。对于您的示例,这将是LArray(0 to 4),总共5个数组元素。零,一,二,三,四是5个数组元素。

使用时,

Size = UBound(LArray) - LBound(LArray) + 1

...这与Size = 4 - 0 + 1相同,正确显示了5个数组元素。但是,当您使用时,

For i = 0 To Size

...您尝试使用LArray(i)访问总共6个数组元素。零,一,二,三,四,五是六个数组元素,而不是5。

解决方案:

始终使用,

for i = lbound(LArray) to ubound(LArray)
    ...
next i

您将永远不会超出该方法的范围。

  1. 使用Option Explicit
  2. 请勿使用On Error Resume Next
  3. “无效”既不是有效的错误代码,也不是错误说明。

代码重写

Option Explicit

Sub main()
    Debug.Print DISCOUNT("1-2,3,4,5-10,23")
End Sub

Function DISCOUNT(quantity) ' "1-2,3,4,5-10,23" is the data in <quantity>
    Dim LString As String
    Dim LArray() As String
    Dim Daysfromto As Variant
    Dim Days As Double
    Dim Totaldays As Double
    Dim i As Long, Contains As Long


    Totaldays = 0
    LString = quantity
    LArray = Split(LString, ",")

    For i = LBound(LArray) To UBound(LArray)
            Contains = InStr(LArray(i), "-")
            If Contains > 0 Then
                Daysfromto = Split(LArray(i), "-")
                Totaldays = Totaldays + CLng(Daysfromto(1)) - CLng(Daysfromto(0)) + 1
            ElseIf Contains = 0 Then
                Totaldays = Totaldays + 1
            End If
            'Debug.Print Totaldays  ' this works here
    Next i

    'Debug.Print Totaldays
    DISCOUNT = Totaldays

End Function