vba 如何使用excel vba代码在工作表列中查找确切的文本字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31672795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:49:32  来源:igfitidea点击:

How to find the exact text string in a column of sheet using excel vba code

excelvbaexcel-vba

提问by ashish vb

How can I find the exact string matching to particular cell value using Excel VBA. For example if I want to search "userid"(whole string only) in column A. I am able to write some lines of code but the program is not able to find the whole word, even if I type some of the letters in the string matching the whole word. Code is as given below:

如何使用 Excel VBA 找到与特定单元格值匹配的确切字符串。例如,如果我想在 A 列中搜索“userid”(仅限整个字符串)。我可以编写一些代码行,但程序无法找到整个单词,即使我在匹配整个单词的字符串。代码如下:

Private Sub CommandButton1_Click()
Dim Username As String, password As String
Dim FindRow1 As Range, FindRow2 As Range
Dim WB As Workbook

Username = "user"
password = "pass"
Set WB = ThisWorkbook

With WB.Sheets("Master_Data")
Set FindRow1 = .Range("A:A").Find(What:=Username, LookIn:=xlValues)
Set FindRow2 = .Range("B:B").Find(What:=password, LookIn:=xlValues)
End With
MsgBox FindRow1
MsgBox FindRow2

Here I am getting output in msgbox as userid and password even if I pass the values as username = "user" and password = "pass" which is logically wrong.

在这里,即使我将值作为 username = "user" 和 password = "pass" 传递,这在逻辑上是错误的,但我在 msgbox 中将输出作为用户 ID 和密码。

回答by Phylogenesis

Use the LookAtparameter of Range.Find():

使用LookAt参数Range.Find()

Set FindRow1 = .Range("A:A").Find(What:=username, LookIn:=xlvalues, LookAt:=xlWhole)
Set FindRow2 = .Range("B:B").Find(What:=password, LookIn:=xlvalues, LookAt:=xlWhole)