我是Excel VBA的初学者
我的问题是,如果我在"MyNameIsHammadAndImFromIreland"
这样的单元格中有字符串。
所有单元格都有字符串/句子,但没有空格。
如何查找单元格是否包含单词"Ireland"
?
答案 0 :(得分:1)
您不需要VBA,只需使用公式:
=IF(LEN(SUBSTITUTE(A1,"Ireland",""))<LEN(A1),"Word Found","Word NOT found")
如果你真的想要VBA那么:
hasWord = InStr(Range("A1").Value, "Ireland") > 0 '// returns TRUE or FALSE
答案 1 :(得分:1)
以下VBA代码将遍历给定工作表中的已用单元格,并找到与给定条件匹配的任何单元格。最后,将显示一个消息框,显示包含搜索词的单元格列表。
此功能相当于使用“查找全部”选项,您可以在按 CTRL + F 使用常规查找功能时选择。
Option Explicit
Private Sub Find()
Dim rngResult As Range
Dim strToFind As String
'Set to your desired string to find
strToFind = "Ireland"
'If the string you are searching for is located in
'the worksheet somewhere, you can set the value
'like this: strToFind = Worksheets("Sheet1").Range("A1").Value
'This assumes your search term is in cell A1 of the
'Sheet1 worksheet.
'Look in the used range of a given worksheet
'Change Sheet1 to match your worksheet name
With Worksheets("Sheet1").UsedRange
'Find the first cell that contains the search term
Set rngResult = .Find(What:=strToFind, LookAt:=xlPart)
'If it is found, grab the cell address of where the
'search term can be found
If Not rngResult Is Nothing Then
Dim firstAddress As String, result As String
firstAddress = rngResult.Address
'Loop through the rest of the cells until returning
'to the first cell that we had a match in.
Do
'Record the cell address of the match
'to the result string
result = result & rngResult.Address & ","
'Go to next cell containing the search term
Set rngResult = .FindNext(rngResult)
'Exit the loop when we reach the starting point
Loop While rngResult.Address <> firstAddress
'Output the list of cells that contain the string to find
MsgBox "Found """ & strToFind & """ in cell(s): " & result
End If
End With
End Sub
务必将strToFind
设置为您想要的字符串,然后更改Sheet1
以匹配您要搜索的工作表的名称。