我正在尝试创建一个在Excel电子表格中搜索文件时使用关键字和文档名称的文档搜索引擎。
它的工作原理是通过空格来分解搜索词和文件名,以及通过逗号来分解关键字。 然后,它为每个关键字匹配每个搜索词,并为每个匹配添加一个计数器。更多的关键字匹配项=更高的计数器,然后我通过该计数器对表格进行排序,这样我可以在顶部获得最匹配的结果。
搜索功能已经可以正常使用,但是当涉及单数和复数术语时,找不到它。
假设doc1的关键字是模板。在搜索字段中搜索词 Template 时,该词不匹配。我正在使用LIKE语句,并且尝试在前端和后端添加通配符,但仍然无法正常工作。
奇怪的是,相反的方法起作用。如果我搜索一个复数词,并且关键字是单数,它将得到一个匹配项。我不知道为什么,这只是一件好事。
Sub Searchresult()
Dim x As Long, y As Long, count As Long
Dim search() As String, keyword() As String, names() As String
Dim result As String
Dim tbl As ListObject, sortcol As Range, lrow As Long
With Worksheets("Sheet3") 'Prep for placing results in table.
Set tbl = .ListObjects("tblSearch")
Set sortcol = .Range("tblSearch[sort]")
tbl.DataBodyRange.ClearContents
End With
With Worksheets("Sheet2")
search = Split(.Range("F1").Value, " ") 'split search terms via spaces
For x = 2 To 1000 Step 1
count = 0
lrow = Worksheets("Sheet3").Cells(Rows.count, 1).End(xlUp).Row + 1
keyword() = Split(.Range("d" & x), ",") ' split keywords via comma
names() = Split(Replace(Replace(Replace(Replace(.Range("c" & x), "-", ""), "(", ""), ")", ""), "'", ""), " ") 'splits names via spaces, deleting any unwanted characters
For i = LBound(keyword) To UBound(keyword)
For j = LBound(search) To UBound(search)
If "*" & UCase(search(j)) & "*" Like "*" & UCase(keyword(i)) & "*" Then 'compare search term and keyword
Worksheets("Sheet3").Range("A" & lrow, "B" & lrow).Value = .Range("A" & x, "B" & x).Value
count = count + 1
Worksheets("Sheet3").Range("C" & lrow).Value = count
End If
Next
Next
For k = LBound(names) To UBound(names)
For l = LBound(search) To UBound(search)
If "*" & UCase(search(l)) & "*" Like "*" & UCase(names(k)) & "*" And Len(names(k)) > 2 Then 'compare search term and document name
Worksheets("Sheet3").Range("A" & lrow, "B" & lrow).Value = .Range("A" & x, "B" & x).Value
count = count + 1
Worksheets("Sheet3").Range("C" & lrow).Value = count
End If
Next
Next
Next
End With
With tbl.Sort 'sort everything based on count to get best result
.SortFields.Clear
.SortFields.Add Key:=sortcol, SortOn:=xlSortOnValues, Order:=xlDescending
.Header = xlYes
.Apply
End With
End Sub
我如何确保LIKE语句可以匹配单词的单数/复数术语?不必太复杂,它可以发现单数/复数(例如:“副本/副本”)时会改变的单词,但是让它与仅添加“ s”的单词匹配就可以。
编辑:感谢Brian的解释,通过添加一个OR语句来固定LIKE语句,从而再次比较这些条件,从而固定了代码。现在,即使单数/复数也可以匹配。
If UCase(search(j)) Like "*" & UCase(keyword(i)) & "*" Or UCase(keyword(i)) Like UCase(search(j)) & "*" Then 'compare search term and keyword
If (UCase(search(l)) & "*" Like UCase(names(k)) & "*" Or UCase(names(k)) Like UCase(search(l)) & "*") And Len(names(k)) > 2 Then
答案 0 :(得分:1)
在您的示例代码中,“关键字”必须为单数形式,然后它将匹配单数形式和复数形式(如您所见)。另外,您在“搜索”字词上也不需要通配符。
"TEMPLATE" Like "*" & "TEMPLATE" & "*" 'returns True
"TEMPLATES" Like "*" & "TEMPLATE" & "*" 'returns True
这样想。在以上两种情况下,我们本质上都是在说“第一项包含第二项。