【发布时间】:2022-07-06 08:18:48
【问题描述】:
我有 2 个数组来自两个包含名称的范围。我想创建第 3 个数组,其中仅包含数组 1 中不在数组 2 中的名称。但是,在尝试将值添加到 集合 时会出现 不匹配类型错误。
这是整个代码:
Sub CrearArreglos()
'**Array2**
Dim Array2() As Variant
Dim iCountLI As Long
Dim iElementLI As Long
If IsEmpty(Range("B3").Value) = True Then
ReDim Array2(0, 0)
Else
iCountLI = (Sheets("Sheet2").Range("B3").End(xlDown).Row) - 2
iCountLI = (Range("B3").End(xlDown).Row) - 2
ReDim Array2(iCountLI)
For iElementLI = 1 To iCountLI
Array2(iElementLI - 1) = Cells(iElementLI + 2, 2).Value
Next iElementLI
End If
'**Array 1:**
Dim Array1() As Variant
Dim iElementLC As Long
Worksheets("Sheet1").Activate
Array1 = Worksheets("Sheet1").Range("BD4:BD10").Value
Dim v3 As Variant
Dim coll As Collection
Dim i As Long
'**Extracting values from Array 1 that are not contained in Array 2**
Set coll = New Collection
For i = LBound(Array1, 1) To UBound(Array1, 1)
If Array1(i, 1) <> 0 Then
'**This line below displays error 13 ↓
coll.Add Array1(i, 1), Array1(i, 1)
End If
Next i
For i = LBound(Array2, 1) To UBound(Array2, 1)
On Error Resume Next
coll.Add Array2(i, 1), Array2(i, 1)
If Err.Number <> 0 Then
coll.Remove Array2(i, 1)
End If
If coll.exists(Array2(i, 1)) Then
coll.Remove Array2(i, 1)
End If
On Error GoTo 0
Next i
ReDim v3(0 To (coll.Count) - 1)
'Adds collection items to a new array:
For i = LBound(v3) To UBound(v3)
v3(i) = coll(i + 1)
Debug.Print v3(i)
Next i
所以这是显示错误 13 的行。如果我删除第二个“Array1(i, 1)”,它运行正常,但它只保存 Array1 中的所有值,它似乎忽略了其余代码和条件)
coll.Add Array1(i, 1), Array1(i, 1)
奇怪的是,过去,当两个范围都在同一张工作表中时,这段代码总是完美工作。这次我从不同的表格中获取范围。我不知道这是否是问题所在,尽管这对我来说没有意义。
如果有任何帮助,我将不胜感激。提前谢谢!
【问题讨论】:
-
如果其中一个值为空(与 0 不同),您可能会收到该错误
-
第二个参数是可选键,必须是字符串。
-
您的代码永远无法完美运行,因为 Collection 对象没有 .Exists 方法。
标签: arrays excel vba collections