类似于VLOOKUP的function:在VBA Excel中为长列表select大小写

Excel VBA中不使用多个If ... Then语句,您可以使用Select Case结构。 但是,如果案件是一个长长的名单,如何有效地执行这项任务? 例如,看看下面的数据:

 Code ID Girls Names 0001 Sophia 0002 Emma 0003 Olivia 0004 Isabella 0005 Ava 0006 Lily 0007 Zoe 0008 Chloe 0009 Mia 0010 Madison 0011 Emily 0012 Ella 0013 Madelyn 0014 Abigail 0015 Aubrey 0016 Addison 0017 Avery 0018 Layla 0019 Hailey 0020 Amelia 0021 Hannah 0022 Charlotte 0023 Kaitlyn 0024 Harper 0025 Kaylee 0026 Sophie 0027 Mackenzie 0028 Peyton 0029 Riley 0030 Grace 0031 Brooklyn 0032 Sarah 0033 Aaliyah 0034 Anna 0035 Arianna 0036 Ellie 0037 Natalie 0038 Isabelle 0039 Lillian 0040 Evelyn 0041 Elizabeth 0042 Lyla 0043 Lucy 0044 Claire 0045 Makayla 0046 Kylie 0047 Audrey 0048 Maya 0049 Leah 0050 Gabriella 0051 Annabelle 0052 Savannah 0053 Nora 0054 Reagan 0055 Scarlett 0056 Samantha 0057 Alyssa 0058 Allison 0059 Elena 0060 Stella 0061 Alexis 0062 Victoria 0063 Aria 0064 Molly 0065 Maria 0066 Bailey 0067 Sydney 0068 Bella 0069 Mila 0070 Taylor 0071 Kayla 0072 Eva 0073 Jasmine 0074 Gianna 0075 Alexandra 0076 Julia 0077 Eliana 0078 Kennedy 0079 Brianna 0080 Ruby 0081 Lauren 0082 Alice 0083 Violet 0084 Kendall 0085 Morgan 0086 Caroline 0087 Piper 0088 Brooke 0089 Elise 0090 Alexa 0091 Sienna 0092 Reese 0093 Clara 0094 Paige 0095 Kate 0096 Nevaeh 0097 Sadie 0098 Quinn 0099 Isla 0100 Eleanor 

我把列表中的代码ID列在AA列和女孩名列表AB列。 我不会使用Select Case结构键入上面的列表,所以我使用下面的代码来完成相同的任务。 它与列A中的部分文本匹配,并在列E中打印结果:

 Sub Matching_ID() ....................................... Dim ID As String, j As Integer, k As Integer, List As Integer List = Cells(Rows.Count, "AA").End(xlUp).Row ID = Mid(Cells(i, "A"), j, 4) For k = List To 2 Step -1 If ID = Cells(k, "AA").Value Then Cells(j, "E") = Cells(k, "AB").Value Exit For Else Cells(j, "E") = "" End If Next k ....................................... End Sub 

虽然上面的代码工作正常,但它是非常耗时的。 有没有更好的办法?

search单个列时,我喜欢使用Match:

 Dim t 'try to find ID t = Application.Match(ID, Range("AA:AA"), 0) 'if not found t will be an error so we test that If Not IsError(t) Then Cells(i, "E") = Cells(t, "AB").Value Else Cells(i, "E") = "" End If 

您可以在VBA中使用VLOOKUP:

 Sub Matching_ID() Dim ID As String, j As Long, i As Long, k As Long, List As Range Dim sht As Worksheet, v Set sht = ActiveSheet Set List = sht.Range(sht.Cells(2, "AA"), sht.Cells(Rows.Count, "AB").End(xlUp)) ID = Mid(Cells(i, "A"), j, 4) 'returns match or an error value if no match v = Application.VLookup(ID, List, 2, False) sht.Cells(j, "E") = IIf(IsError(v), "", v) End Sub