简体   繁体   中英

How to categorize a text string based on keywords in Excel using VBA?

I am working on creating a macro using VBA to read a long list of columns (approximately 11,000) and assign each row to a "category" by finding keywords within the text in each cell. The text in each file is related to a warranty claim, and the idea is by determining is a cell has 3 or 4 matches from a list of "keywords" it can be lumped into a bucket.

Below is the code I am trying to use right now. Where I am running into issues, is if I try to create a list of additional keywords ("injector" is current keyword below) and edit the > function afterwards to be a number greater than zero.

The code below is working for single keywords.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 28 Then
        If InStr(1, UCase(Target.Value), "INJECTOR") > 0 Then
            Cells(Target.Row, 53) = "DEF leak from tip"
        End If
        If InStr(1, UCase(Target.Value), "HARNESS") > 0 Then
            Cells(Target.Row, 53) = "Internal DEF leak affecting wire harness"
        End If
    End If
End Sub

Example of what I am looking to do:

Here's one possible approach:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim v, classn
    
    If Target.CountLarge > 1 Then Exit Sub
    If Target.Column <> 28 Then Exit Sub
    
    v = Target.Value
    If Len(v) = 0 Then Exit Sub
    
    'would be better to keep these lists and classifications on a worksheet and get them from there...
    If MatchCount("injector,item2,item3", v) > 1 Then classn = "DEF leak from tip"
    If MatchCount("item4,item5,item6", v) > 1 Then classn = "other thing"
    'etc
    
    Target.EntireRow.Cells(53).Value = classn

End Sub

Function MatchCount(lst As String, txt)
    Dim arr, e, n As Long
    arr = Split(lst, ",") 'get array from list
    For Each e In arr
        n = n + IIf(InStr(txt, e) > 0, 1, 0) 'track match count
    Next e
    MatchCount = n
End Function

Instead of hard-coding keywords and classifications in the event handler, you could consider storing them on a worksheet and reading them from there.

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