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
相关产品推荐
相关产品推荐

