VBA数组中Application.Match对比循环的性能优势及适用场景
判断Excel VBA数组中值是否存在:Application.Match vs 循环的适用场景
当需要判断Excel VBA数组中是否存在某个值时,我曾使用Application.Match函数编写了IsInArrayWithMatch函数:
Function IsInArrayWithMatch(ByVal Val As Variant, ByRef MyArray As Variant) IsInArrayWithMatch = Not IsError(Application.Match(Val, MyArray, 0)) End Function
为验证该方法是否最优,我编写了循环实现的IsInArrayWithLoop函数:
Function IsInArrayWithLoop(ByVal Val As Variant, ByRef MyArray As Variant) As Variant If Not IsArray(MyArray) Then IsInArrayWithLoop = CVErr(xlErrValue) End If Dim i As Long For i = LBound(MyArray) To UBound(MyArray) If Val = MyArray(i) Then IsInArrayWithLoop = True Exit Function End If Next End Function
随后使用VBA-Benchmark进行两次基准测试:
- 第一次针对内存数组,循环方法速度约为
Application.Match的100倍; - 第二次针对Range转换的数组,循环方法仍快30倍。
既然循环性能更优,还有哪些场景或理由应优先使用Application.Match?
优先选择Application.Match的场景
- 代码简洁易维护:仅需一行核心代码即可实现存在性判断,无需编写循环结构、边界检查等冗余代码,可读性和维护性更高,适合快速实现需求的场景。
- 直接处理多维度数组/Range对象:对于二维数组或直接操作Range区域时,
Match可通过参数指定查找方向(行/列),无需手动处理维度索引;若直接对Range操作,甚至不需要先转换为内存数组,减少代码步骤。 - 附带位置返回值:除了判断存在性,
Match还会返回匹配值的位置索引,若后续业务需要用到该位置,无需在循环中额外记录,直接复用Match结果即可。 - 原生兼容Excel数据类型:
Match遵循Excel原生数据处理逻辑,对日期、文本数字混合、错误值等特殊类型的匹配兼容性更好,无需手动处理类型转换问题。 - 自动处理数组边界:无需手动调用
LBound和UBound,Match会自动识别数组的有效范围,避免因边界判断失误导致的循环错误。
内容的提问来源于stack exchange,提问作者DecimalTurn
相关产品推荐
相关产品推荐

