如何使用excel vba代码在工作表中find确切的文本string

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

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中的输出作为userid和password,即使我将这些值作为username =“user”和password =“pass”传递,这在逻辑上是错误的。

使用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)