【问题标题】:Excel VBA: Why am I getting a run-time error 438 when adding custom class object into custom class array?Excel VBA:为什么将自定义类对象添加到自定义类数组时出现运行时错误 438?
【发布时间】:2020-05-04 17:17:19
【问题描述】:

我知道这里和其他地方还有一些关于此错误的其他帖子,但导致问题的原因似乎无处不在,到目前为止我看到的解决方案似乎都没有解决问题我正在面对。

我有一个类模块,代码如下:

Public questionID As Integer
Public score As Double
Public time As Date
Private lines() As New Line                'If I remove 'New', I end up getting Run-time error 91 instead

Sub CreateByRow(row As Range)
    questionID = row.Cells(1, 1)
    score = row.Cells(1, 7)
    time = row.Cells(1, 8)

    ''' INSERT LINES '''
    Dim tLines As ListObject
    Set tLines = shtLines.ListObjects("lines")

    Erase lines

    Dim rLine As Range
    For Each rLine In tLines.Range.Rows
        If rLine.Cells(1, 1) = questionID Then
            Dim ln As New Line
            ln.CreateByRow rLine           'Line object is created as expected

            u = UBound(lines) + 1          'u = 0 as expected
            ReDim lines(u)                 'Array has a length of 1 and index of 0 as expected
            lines(u) = ln                  'This is where the error happens
        End If
    Next
End Sub

当我运行这段代码时,我得到了运行时错误 438,但我不明白为什么。该数组正在寻找Line 对象。我试图放入的Line 对象不为空。

当我在给我问题的行上暂停时:

【问题讨论】:

  • Set lines(u) = ln 此外,ReDim lines(u) 将删除您数组中的任何现有内容 - 您需要使用 ReDim Preserve 来避免这种情况。
  • 你知道的。现在我很生气,解决方案如此简单。我希望有更大的东西。我真的不明白Set 的关键字是什么,什么时候应该使用它。感谢您的帮助。
  • 是的,我意识到我第一次运行时忘记添加Preserve
  • "在 VBA 中,必须使用 Set 关键字来区分对象的赋值和对象的默认属性的赋值。" docs.microsoft.com/en-us/previous-versions/office/developer/… 可能还有 stackoverflow.com/questions/9481140/…
  • 当然,对于一维数组,如果您使用 Collection 或 Dictionary 代替数组,那么所有 redim 保留恶作剧的痛苦都会被消除。

标签: arrays excel vba runtime-error


【解决方案1】:
Set lines(u) = ln

发件人:https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2003/aa192490(v=office.11)?redirectedfrom=MSDN

“在 VBA 中,Set 关键字是区分对象赋值和对象默认属性赋值所必需的。”

因为这在 VBA 中可以正常工作:

Dim a
a = Range("a1")   'implicitly uses default property: Range("A1").Value

...当您想在 a 中获取对实际 Range 对象(而不是其值)的引用时,您需要使用 Set 来告诉运行时您真正想要什么:

Set a = Range("a1")

因此,使用Set 的需要是具有Value 等默认属性的“便利”的副作用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多