简体   繁体   中英

Excel VBA Compare Array

I am new to VBA and I tried to put the two tables into arrays. One is master and one is the source. I want to compare the two arrays and bring over the price from the source array to master array. Leave the cells blank if the variables are not the same. Please help, I need some tips/advice.

桌子

Sub createarray()
    Dim masterarray(11, 3) As Variant
    Dim sourcearray(25, 3) As Variant

    For i = 1 To 25
        sourcearray(i, 1) = Range("H" & i + 2)
        sourcearray(i, 2) = Range("I" & i + 2)
        sourcearray(i, 3) = Range("J" & i + 2)
        Debug.Print sourcearray(i, 1); sourcearray(i, 2); sourcearray(i, 3)
    Next

    For i = 1 To 11
        masterarray(i, 1) = Range("D" & i + 2)
        masterarray(i, 2) = Range("E" & i + 2)
        masterarray(i, 3) = Range("F" & i + 2)
        Debug.Print masterarray(i, 1); masterarray(i, 2); masterarray(i, 3)
    Next
End Sub

Why don't you use vlookup and Concat functions instead of VBA? Your code need to improve several lines to work like: define better the arrays and nest the for loops, and create a conditional If to compare both tables

'Note: This is a code example no exactly what you need
 Sub createarray()
    Dim i, j as integers
    Dim wb As Workbook
    Dim masterarray As Range: Set wb.worksheet("sheet1").Range("D3:F12")
    Dim sourcearray As Range: Set wb..worksheet("sheet1").Range("H3:J26")

    'You'll need to concat Cost Centry and Variables

    For i = 1 To 11
        For j = 1 to 25
            If masterarray(i, 2).value = sourcearray(j, 2).value then
                masterarray(i, 3).value = sourcearray(j, 3).value
            Else
                masterarray(i, 3).value = ""
            End If
        Next j
    Next i
End Sub

or option two

Use Concat to merge "Cost Centre" & "Variables" in "C3" cell as: =$D$3&E3 and fill down you will get something like this:

|104Enhacement |

|104IT Operations|

|... |

in "G3" do the same =$H$3&I3 and fill down (be careful when "Call Centre" code change) you will get something like this:

|106Enhacement |

|106IT Operations|

|... |

|104Enhacement |

|104IT Shared Services|

|... |

then in "F3" cell use =iferror(vlookup("C3","$G$3:$J$26",4,0),"")

Because you are using "Format as table" probably the function change a little bit but it is not a big issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM