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

时间:2015-07-28 09:48:14

标签: excel vba excel-vba

如何使用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

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

1 个答案:

答案 0 :(得分:14)

使用Range.Find()LookAt参数:

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