You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA排序Variant数组后取元素出现Subscript Out of Range错误求助

VBA排序数组下标越界问题

我从Excel文件读取11个值到Variant类型的vector变量中,对其排序后尝试获取数组元素,尽管下标小于UBound(sorted_vector)返回的11,仍触发"Subscript Out of Range"错误。

出错代码

Function get_value_from_sorted_array(vector As Variant) As Variant
    ReDim sorted_vector(WorksheetFunction.CountA(vector)) As Variant
    sorted_vector = WorksheetFunction.sort(vector)
    
    Dim sorted_vector_ubound As Double
    sorted_vector_ubound = UBound(sorted_vector) '返回值为11
    
    get_value_from_sorted_array = sorted_vector(5) '触发下标越界错误
End Function

问题原因

WorksheetFunction.Sort返回的是二维数组,即便原输入是一维数据,返回结果的维度结构也是(1到元素个数, 1),直接使用一维下标访问会导致维度不匹配,触发错误。

解决方案

使用二维下标访问数组元素,例如:

get_value_from_sorted_array = sorted_vector(5, 1)

内容的提问来源于stack exchange,提问作者sleepy4505

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 10:42:36