仅在搜索期间删除字符?

时间:2014-08-18 10:18:53

标签: excel excel-vba vba

我有一个excel文件,就像一个包含大量Q& A的常见问题解答。在第一个工作表上有一个搜索功能。输入要搜索的单词,然后按Enter键。然后,该函数在整个工作簿中查找这些单词。为了能够进行正确的搜索,我必须删除所有句号,逗号,感叹号和问号。

我使用Replace来做这件事,但并没有真正想到后果。这些字符会从文本中永久删除,这使得它看起来有点难以阅读和丑陋。

所以我的问题是,如何才能在搜索过程中删除这些字符?我是否必须将每个文本复制到新单元格并在那里进行搜索,还是有其他方法?

这是我删除字符和最终搜索的功能的一部分。

Function FindWords(cellToSearch As Range, nOfWords As Integer, myWords As String) As Long

Dim counter As Long
Dim word, element
Dim arr, wordsArr

cellToSearch = Replace(cellToSearch, Chr(33), "")
cellToSearch = Replace(cellToSearch, Chr(44), "")
cellToSearch = Replace(cellToSearch, Chr(46), "")
cellToSearch = Replace(cellToSearch, Chr(63), "")

wordsArr = Split(myWords)
arr = Split(cellToSearch)

If UBound(arr) > 0 Then
    For Each word In wordsArr
        For Each element In arr
            If LCase(word) = LCase(element) Then counter = counter + 1
        Next
    Next
Else
    ' cell to search is empty
    counter = 0
End If

If counter = nOfWords Then
    FindWords = 1
Else
    FindWords = 0
End If

End Function

1 个答案:

答案 0 :(得分:2)

你可以使用另一个变量:

Function FindWords(cellToSearch As Range, nOfWords As Integer, myWords As String) As Long

Dim counter As Long
Dim word, element
Dim arr, wordsArr
Dim sFindWord as String
sFindWord = cellToSearch.Value
sFindWord = Replace(sFindWord , Chr(33), "")
sFindWord = Replace(sFindWord , Chr(44), "")
sFindWord = Replace(sFindWord , Chr(46), "")
sFindWord = Replace(sFindWord , Chr(63), "")

wordsArr = Split(myWords)
arr = Split(sFindWord)

If UBound(arr) > 0 Then
    For Each word In wordsArr
        For Each element In arr
            If LCase(word) = LCase(element) Then counter = counter + 1
        Next
    Next
Else
    ' cell to search is empty
    counter = 0
End If

If counter = nOfWords Then
    FindWords = 1
Else
    FindWords = 0
End If

End Function