VBA数据类型不匹配

时间:2018-04-12 18:13:43

标签: arrays excel vba excel-vba

我正在使用Dates作为我的数据,我认为这可能会导致一些问题。

Sub test()

    Dim counter As Long
    For counter = 1 to 10

        Dim fltArr(0 to 9)
        Dim X 
        Dim Largest As Date

        For items = 3 to 12
        fltArr(items-3) = Cells(items, 6)
        Next

        X = fltArr
        Largest = Application.Large(X, counter)

    Next
End Sub

错误似乎出现在行

Largest = Application.Large(X, counter)

我认为这可能是由于Application.Large给出了一个整数而不是Date。我怎么能解决这个问题?

2 个答案:

答案 0 :(得分:2)

Value2属性与Value属性之间的唯一区别是Value2属性不使用CurrencyDate数据类型。您可以使用Double数据类型将使用这些数据类型格式化的值作为浮点数返回。 Reference

您所要做的就是更改行

fltArr(items-3) = Cells(items, 6)

fltArr(items-3) = Cells(items, 6).Value2

试试这个

Sub test()
    Dim counter As Long
    Dim Largest As Date

    For counter = 1 To 10
        Dim fltArr(0 To 9) As Variant
        Dim X As Variant

        For items = 3 To 12
            fltArr(items - 3) = Cells(items, 6).Value2
        Next

        X = fltArr

        Largest = Application.Large(X, counter)
        Debug.Print Largest
    Next
End Sub

答案 1 :(得分:1)

Large不喜欢使用Date Arrays。如果将数组声明为双精度数,它将返回所需的值(使用代码):

Sub test()

    Dim counter As Long
    For counter = 1 To 10

        Dim fltArr(0 To 9) As Double
        Dim X() As Double
        Dim Largest As Date

        For items = 3 To 12
        fltArr(items - 3) = Cells(items, 6)
        Next

        X = fltArr
        Largest = Application.Large(Range("F3:F12"), counter)
        Debug.print Largest

    Next
End Sub