VBA *通配符* Vlookup - 或替代

时间:2015-01-13 06:23:51

标签: excel-vba replace find wildcard vlookup

我希望使用Vlookup函数编写一些代码,以便将值返回到相邻列。但是我希望查找能够使用通配符,即不需要完全匹配。

下面的代码将逐行向下看D列,然后使用该值从数据表中查找相应的值并将其返回到E列。这种方法有效,但无法很好地处理缺失或不正确的值。 / p>

D栏中的数据将是全文格式句子,所以我只需要查找关键词然后返回一个设定的参考值进行数据处理。

    Sub LookUpComments() 'exact match only ???

On Error Resume Next
Application.ScreenUpdating = False

    Dim DataRow As Long
    Dim DataClm As Long
    Dim Result As Variant

DataTable = Sheet3.Range("D5:D35")
LookUpTable = Sheet3.Range("AA10:AB20")
Sheet3.Range("E5:E10000").ClearContents

DataRow = Sheet3.Range("E5").Row
DataClm = Sheet3.Range("E5").Column

For Each cl In DataTable

        If cl = "" Then GoTo E
        Result = Application.WorksheetFunction.VLookup(cl, LookUpTable, 2, blnLookupType)
        If Result = Error Then GoTo E
        Sheet3.Cells(DataRow, DataClm) = Result

E:            DataRow = DataRow + 1
Next cl

Application.ScreenUpdating = True
MsgBox "Data LookUp is complete"

End Sub

我希望我已经说清楚了吗?如果无法使用此功能,您认为我可以使用某种循环查找和替换功能吗?

提前致谢

2 个答案:

答案 0 :(得分:0)

如果像使用Vlookup一样将blnLookupType设置为true并不能提供所需的结果,则可以使用Range.Find,然后使用Offset返回所需的值。它支持通配符,您可以搜索字符串或整体的任何部分。见下面的例子。

Sub FindingPart()

Dim rng As Range, found As Range
Set rng = Sheet2.Range("A:A")

Set found = rng.Find(What:="as", LookAt:=xlPart) 'Will find for example "bass"
If Not found Is Nothing Then returnValue = found.Offset(0, 1)

End Sub



Sub FindingWildCards()

Dim rng As Range, found As Range
Set rng = Sheet2.Range("A:A")

Set found = rng.Find(What:="as*", LookAt:=xlWhole) 'Would find for example "ashes" but not "bass"
If Not found Is Nothing Then returnValue = found.Offset(0, 1)

End Sub

答案 1 :(得分:0)

感谢您的建议,看起来我只是用VLookup走错了路。

我现在已经完成了一个完全符合我需要的代码,尽管我确信它可以写得更好。我使用vlookup获取每个搜索条件的返回值,然后为每个搜索条件循环查找/替换。

Sub FilterComments()

On Error Resume Next

Dim Rng As Range, found As Range
Dim Rtn As String

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

    LookUpValue = ActiveWorkbook.Sheets("LOOKUP").Range("I10:I108")
    LookUpTable = ActiveWorkbook.Sheets("LOOKUP").Range("I10:J108")

ActiveWorkbook.Sheets("IEOutput").Range("W:W").Value = ActiveWorkbook.Sheets("IEOutput").Range("T:T").Value
ActiveWorkbook.Sheets("IEOutput").Range("W1").Value = "LOOKUP COMMENT"

Set Rng = ActiveWorkbook.Sheets("IEOutput").Range("W:W")

        For Each cl In LookUpValue
        If cl = "" Then GoTo E

            Rtn = Application.VLookup(cl, LookUpTable, 2, False)


            Rng.Replace What:="*" & cl & "*", Replacement:=Rtn, LookAt:=xlPart, _
                SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
                ReplaceFormat:=False
E:
        Next cl


Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
MsgBox "Data LookUp is complete", vbInformation, "GM PMS Data Filter"

End Sub

希望这有助于其他试图做类似事情的人