简体   繁体   中英

Excel VBA - How to search array and return value?

I have some data that looks like this (starting in A1):

Batman
Carl Reiner
Ford
Sushi

But I have a two dimensional array, storing those names, and their type:

Dim Names()
ReDim Names(4,1)
Names(0,0) = "Batman"
Names(0,1) = "Superhero"
Names(1,0) = "Carl Reiner"
Names(1,1) = "Comedian"
Names(2,0) = "Ford"
Names(2,1) = "Car Manufacturer"
Names(3,0) = "Sushi"
Names(3,1) = "Food"

Now, I would like to loop through column A and replace those data points with their equivalent type. I thought there would be a relatively simple way to essentially search Names(x,0) for "Batman" then just replace it with Names(x,1). What's the best way to do so?

I found somewhere that you could possibly use Vlookup with this, so I tried this, to no avail:

Evaluate(WorksheetFunction.Vlookup("A1",Names,1,False)

With my thought being it would look for "Batman" and return the value in Names in the "1" dimension...But that keeps giving me an error (Type 13 Mismatch).

Thanks for any ideas/help!

edit: I found this post and seem to be getting somewhere with Application.Match("A1",Application.Index(Names,0,1),0) which returns the position of "A1" in the array. Now I just need to return the offset and get the "1" position of that...

Edit 2: I think I got it. Using MATCH to find the position of "A1" then just use the array to find it:

Names(Application.Match("A1",Application.Index(Names,0,1),0),1)

So, when A1 is Batman, it finds that position in the index, then it finds the equivalent return in the second dimension. (Sorry for the lack of semantics, I don't have a very good idea of how to refer to this, so please let me know if I can clarify).

It seems like this would be easier using a Dictionary.

Sub testing()
    Dim dic As Object
    Set dic = CreateObject("scripting.dictionary")

    With dic
        .Add "Batman", "Superhero"
        .Add "Carl Reiner", "Comedian"
        .Add "Ford", "Car Manufacturer"
    End With

    MsgBox "Batman is a " & dic.Item("Batman")

End Sub

I think if you want to use worksheet functions, you have to put the data into a worksheet (eg a column or pair of columns) instead of an array. This is pretty easy to do, though, and you can use a different worksheet, or even another workbook, and there are solutions to hide these, so your users don't have to see that data cluttering the other worksheets.

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