VBA自定义Type内数组初始化与使用报错求助
解决VBA嵌套自定义类型中数组下标越界问题
问题根源
你遇到的下标越界错误,是因为**CommentLine数组尚未初始化(未执行过ReDim分配内存)**,此时直接调用UBound(.Comment.CommentLine)会触发错误。而ElementAttribute数组能正常运行,是因为你直接通过ReDim Preserve .ElementAttribute(i)完成了数组的初始化,没有先去访问未初始化数组的边界值。
解决方案
需要先判断嵌套数组是否已初始化,再执行扩容操作。以下提供两种可行写法:
写法1:通过错误捕获处理初始化
With myXmlElement .ElementName = "name" .ElementValue = "Nick" Dim currentUpper As Long On Error Resume Next ' 尝试获取数组上界,未初始化会触发错误 currentUpper = UBound(.Comment.CommentLine) If Err.Number <> 0 Then ' 数组未初始化,先分配第一个元素的内存(适配你的Option Base 1设置) ReDim .Comment.CommentLine(1 To 1) Else ' 数组已初始化,扩容 ReDim Preserve .Comment.CommentLine(1 To currentUpper + 1) End If On Error GoTo 0 ' 写入新的注释内容 .Comment.CommentLine(UBound(.Comment.CommentLine)) = "nice" End With
写法2:用自定义函数判断数组是否初始化
先定义一个工具函数,用来检测数组是否已分配内存:
Private Function IsArrayAllocated(arr As Variant) As Boolean On Error Resume Next IsArrayAllocated = IsArray(arr) And (UBound(arr) >= LBound(arr)) On Error GoTo 0 End Function
然后在业务代码中使用:
With myXmlElement .ElementName = "name" .ElementValue = "Nick" ' 检查数组是否初始化,未初始化则先分配内存 If Not IsArrayAllocated(.Comment.CommentLine) Then ReDim .Comment.CommentLine(1 To 1) End If ' 扩容并写入内容 ReDim Preserve .Comment.CommentLine(1 To UBound(.Comment.CommentLine) + 1) .Comment.CommentLine(UBound(.Comment.CommentLine)) = "nice" End With
关键注意点
- VBA中动态数组必须通过
ReDim分配内存后才能使用,嵌套在自定义类型中的数组也不例外 - 如果你使用了
Option Base 1(从代码中myArray的索引方式可判断),初始化数组时建议显式指定下标范围(如1 To 1),避免默认下界0带来的混淆
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

