繁体   English   中英

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

[英]Find word in part of cell text, return column number: Excel VBA

我的目标是在Excel中以用户形式实现搜索功能。

它应该能够接受在TextBox输入的单词,并遍历特定行中的每一列并搜索该单词。 然后,它应该返回首次发现它的列。

在下面的代码中,它将仅查看单元格内容的完全匹配情况。 但是,如果单元格值是例如:“ Lorem ipsum,dolor sitamet”-我希望能够搜索“ 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)


您还可以使用符号( & )整理返回的结果,它连接字符串:

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

您说要在“特定行中的每一列”中搜索,但是要在“特定列中的前100行”中搜索? 不确定这是拼写错误还是您的代码错误。 无论哪种方式,都可以使用“ Rows或“ Columns对象。 这些应该与完全限定您的范围一起使用,即说出它在哪里。

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.仅执行一次搜索,

现在,如果您能提升我的水平。

执行此操作的最简单代码-根据所选范围-Range(“ D1:D100”),您只会在该值存在的地方找到行号。 为了也找到列号,请扩大范围。

就是这个 -

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM