从2个不同大小的数组创建第3个数组

时间:2019-09-16 14:44:22

标签: excel vba

我正在尝试从数组A和数组B创建第三个数组,其中数组B包含在数组A中。为了简短起见,我将在此处发布循环,我想要的数组是正确的,我已经打印它们并确认它们是正确的。在我的循环中它出了点问题。

Array A: [a1, a2, a3, b1, b2, b3, c1, c2, c3] 
Array B: [a1, a2, a3, b1, b3, c1, c2] 
Array C (what I want): [a1, a2, a3, b1, N/A, b3, c1, c2, N/A]

我认为我的错误来自于下一个我放置的地方。我无法将其放在If语句中,但不确定该去哪里。

For j = 1 To UBound(EASR_VI_New)
    For i = 1 To UBound(VI_VRR4)
        If VI_VRR4(i, 1) = EASR_SS_VI_All(j, 1) Then
            TE_VRR4E(i, 1) = TE_VRR4F(i, 1)
        ElseIf VI_VRR4(i, 1) <> EASR_SS_VI_All(j, 1) Then
            TE_VRR4E(i, 1) = "N/A"
        End If
    Next i
Next j

当前,阵列TE_VRR4E正在打印所有N / A,但是当我打印VI_VRR4和EASR_SS_VI_时,每个阵列中的所有前3个值完全相同。所以我不知道为什么会给我全部不适用。

2 个答案:

答案 0 :(得分:2)

它放置所有N/A,因为即使找到匹配项,它仍继续循环并检查。然后,下一个循环用N/A覆盖正确的返回值,因为数组B中的下一个值不等于被测试数组A中的值。

默认N/A,如果为正则退出循环。

For i = 1 To UBound(VI_VRR4)
    TE_VRR4E(i, 1) = "N/A"
    For j = 1 To UBound(EASR_VI_New)        
        If VI_VRR4(i, 1) = EASR_SS_VI_All(j, 1) Then
            TE_VRR4E(i, 1) = TE_VRR4F(i, 1)
            Exit For
        End If
    Next j
Next i

要显示其效果,

Dim A As Variant, B As Variant, C As Variant, i As Long, j as Long

A = ActiveSheet.Range("A1:A9").Value
B = ActiveSheet.Range("B1:B7").Value

ReDim C(1 To UBound(A, 1), 1 To 1)

For i = 1 To UBound(A, 1)
    C(i, 1) = "N/A"
    For j = 1 To UBound(B, 1)
        If A(i, 1) = B(j, 1) Then
            C(i, 1) = A(i, 1)
            Exit For
        End If
    Next j
Next i

ActiveSheet.Range("D1").Resize(UBound(A, 1), 1).Value = C

enter image description here


顺便说一句:可以使用一个简单的公式完成相同的输出:

=IFERROR(VLOOKUP(A1,B:B,1,FALSE),"N/A")

enter image description here

答案 1 :(得分:2)

Scott已经诊断出您的问题。

我之所以发表这篇文章只是因为它是避免2次循环的一种方式。

Sub x()

Dim A As Variant, B As Variant, C() As String, i As Long

A = Array("a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3")
B = Array("a1", "a2", "a3", "b1", "b3", "c1", "c2")

ReDim C(UBound(A))
For i = LBound(A) To UBound(A)
    If IsNumeric(Application.Match(A(i), B, 0)) Then
        C(i) = A(i)
    Else
        C(i) = "N/A"
    End If
Next i

Range("A1").Resize(, i) = C

End Sub

enter image description here