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

VBA数组填充跨数组赋值时抛出TypeMismatch类型不匹配错误

问题根因

该类型不匹配错误属于代码笔误导致,和Variant类型声明无关:

  • 函数内声明的vItemsNotInMaster仅为普通Variant类型变量,从未通过ReDim语句初始化为数组结构,始终是空值状态,无法通过下标语法(k)执行元素赋值操作,因此触发报错。
  • 代码实际提前初始化、最终作为函数返回值的结果数组名为vArray3,写元素赋值逻辑时错写为未初始化的vItemsNotInMaster,是典型的变量名书写错误。
解决方法

直接修正笔误即可,无需调整变量类型定义:

  1. 将报错行的变量名替换为已完成初始化的结果数组名,即把vItemsNotInMaster(k) = vCheckItems(i)修改为vArray3(k) = vCheckItems(i)
  2. 可选优化:删除全程未使用的多余变量vItemsNotInMaster,避免后续再出现同类笔误。

修正后的完整函数代码如下:

Public Function Comparing_TwoArrays(ByVal vCheckItems As Variant, ByVal vMasterList As Variant) As Variant

   Dim vArray3 As Variant
   Dim isMatch As Boolean
   Dim i As Integer
   Dim j As Integer
   Dim k As Integer
   
   ReDim vArray3(1 To UBound(vCheckItems, 1) + UBound(vMasterList, 1))
   k = 1
   
   For i = LBound(vCheckItems, 1) To UBound(vCheckItems, 1)
       isMatch = False
       
       For j = LBound(vMasterList, 1) To UBound(vMasterList, 1)
           If vCheckItems(i) = vMasterList(j) Then
               isMatch = True
               Exit For
           End If
       Next j
       
       If (isMatch = False) Then
           vArray3(k) = vCheckItems(i) ' 修正变量名后不再报错
           k = k + 1
       End If
   Next i
   
   If (k > 1) Then
      ReDim Preserve vArray3(1 To k - 1)
   Else
      vArray3 = Empty
   End If
   
   Comparing_TwoArrays = vArray3

End Function

修正后代码执行逻辑符合预期:会返回第一个数组中存在、第二个数组中不存在的所有元素组成的数组,本次测试用例返回结果为包含"three5"的单元素数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 15:18:13