VBA判断数组首项是否为空及空数组赋值报错问题排查
解决VBA空数组赋值时的错误9(下标越界)问题
我来帮你理清这个问题的根源和解决办法:
错误9的核心原因
当你所有的源单元格都是空值时,For循环里的ReDim Preserve commentResults(b)语句根本不会执行——这意味着commentResults是一个未初始化的动态数组,它没有被分配任何内存空间。这时候你试图用UBound、LBound,甚至直接访问commentResults(0),都会触发「下标越界」错误(错误9)。
你之前尝试的两种判断方式之所以失效,也是因为这个原因:
- 第一种
IsError(Application.Match("*", (commentResults), 0)):当数组未初始化时,Application.Match无法处理这个无效参数,直接报错。 - 第二种
If commentResults(0) <> vbNullString Then:同样,数组没初始化,访问下标0直接触发错误9。
正确的解决方案
其实你已经有一个天然的判断依据——变量b。因为b初始值为0,只有当找到非空元素时才会递增。所以直接判断b > 0就能知道commentResults是否有有效元素。
另外还要注意一个细节:VBA的一维数组默认是**纵向(列方向)**的,如果直接赋值给横向的单元格区域(用Resize(columnsize:=...)),元素会被写入同一列的不同行,而不是同一行的连续列。所以需要用Application.Transpose把数组转成横向的。
修改后的完整代码如下:
Dim commentArray(4) As Variant commentArray(0) = Cells(24, 4).Value commentArray(1) = Cells(25, 3).Value commentArray(2) = Cells(26, 3).Value commentArray(3) = Cells(27, 3).Value Dim a As Long, b As Long Dim commentResults() As Variant ' 移除空值并构建结果数组 For a = LBound(commentArray) To UBound(commentArray) If commentArray(a) <> vbNullString Then ReDim Preserve commentResults(b) commentResults(b) = commentArray(a) b = b + 1 End If Next a ' 用b的值判断是否有有效元素 If b > 0 Then ' 转置数组后写入横向单元格区域 thisws.Cells(i, 19).Resize(columnsize:=b).Value = Application.Transpose(commentResults) b = 0 Else ' 没有元素时清空目标单元格(按需调整) thisws.Cells(i, 19).ClearContents End If
额外的数组初始化判断方法
如果你不想依赖b变量,也可以写一个自定义函数来判断数组是否被初始化:
Function IsArrayAllocated(arr As Variant) As Boolean On Error Resume Next IsArrayAllocated = IsArray(arr) And Not IsError(LBound(arr)) And LBound(arr) <= UBound(arr) On Error GoTo 0 End Function
使用时直接判断:
If IsArrayAllocated(commentResults) Then thisws.Cells(i, 19).Resize(columnsize:=UBound(commentResults)-LBound(commentResults)+1).Value = Application.Transpose(commentResults) End If
不过用b的方式更简洁,因为你已经在用它计数了,没必要多写一个函数。
内容的提问来源于stack exchange,提问作者Alex H
相关产品推荐
相关产品推荐

