在部分单元格文本中查找单词,返回列号:Excel VBA

我的目标是在Excel中以用户forms实现searchfunction。

它应该能够在TextBoxinput一个单词并遍历特定行中的每一列并search该单词。 那么它应该返回最初发现的列。

使用下面的代码,它只会查看单元格内容的完全匹配。 但是如果单元格的值是例如:“Lorem ipsum,dolor sitamet” – 我想能够search“dolor”。

这是我的代码:

 Dim rFind As Range With Range("D1:D100") Set rFind = .Find(What:=TextBox13.Value, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False) If Not rFind Is Nothing Then MsgBox rFind.Column MsgBox rFind.Row End If End With 

只需将LookAt:=xlWhole更改为LookAt:=xlPart

文档: Range.Find方法(Excel)


您还可以使用&符号( & )来整理返回的结果,并将string连接起来:

 "Col: " & rFind.Column & ", Row: " & rFind.Row ' For example, gives the string "Col: 1, Row: 1" if found in A1 

你说你想search“特定行中的每一列”,但是你正在查看“特定列中的前100行”? 不知道这是一个错字还是你的代码是错误的。 无论哪种方式,您都可以使用RowsColumns对象。 这些应该用于完全限定你的范围,即说出它的位置。

 ThisWorkbook.Sheets("Sheet1").Rows(1) ' Range of entire first row ThisWorkbook.Sheets("Sheet1").Columns(1) ' Range of entire first column ThisWorkbook.Sheets("Sheet1").Columns("A") ' Equivalent, range of entire first column 

改写:

 Dim rFind As Range With ThisWorkbook.Sheets("Sheet1").Columns("D") Set rFind = .Find(What:=TextBox13.Value, LookAt:=xlPart, MatchCase:=False, SearchFormat:=False) If Not rFind Is Nothing Then MsgBox "Col: " & rFind.Column & ", Row: " & rFind.Row End If End With 

这部分

 LookAt:=xlWhole 

应该

 LookAt:=xlPart 

看起来好像你想检查每个单词 – 这将做到这一点:

 Sub Check() Dim vWords As Variant Dim sCheck As String Dim rFind As Range Dim i As Long sCheck = "Lorem ipsum, dolor sitamet" ' TextBox13.Value sCheck = Replace(sCheck, ",", "") vWords = Split(sCheck, " ") For i = 0 To UBound(vWords) With Range("D1:D100") Set rFind = .Find(What:=Trim(vWords(i)), LookAt:=xlPart, MatchCase:=False, SearchFormat:=False) If Not rFind Is Nothing Then MsgBox rFind.Column MsgBox rFind.Row End If Set rFind = Nothing End With Next End Sub 

代码更新:对于所有评论,1.添加了xlPart 2.只执行一个search,

现在如果你能提高我的话。

最简单的代码 – 按照您select的范围 – 范围(“D1:D100”),您只能find存在值的行号。 为了find列号,扩大你的范围。

就是这个 –

 Sub find_code() Dim add As String On Error Resume Next add = Range("D1:D100").Find(TextBox1.Text, Lookat:=xlPart, MatchCase:=False).AddressLocal If Err.Number <> 0 Then MsgBox "Empty Search result", vbInformation Exit Sub End If MsgBox Range(add).Row MsgBox Range(add).Column End Sub