2015-07-28 20 views
3

如何使用Excel VBA查找與特定單元格值匹配的確切字符串。例如,如果我想在A列中搜索「userid」(僅限整個字符串),我可以編寫一些代碼行,但程序無法找到整個單詞,即使我在其中鍵入了一些字母字符串匹配整個單詞。 代碼是,如下所示:如何使用excel vba代碼在工作表中找到確切的文本字符串

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作爲用戶名和密碼輸出,即使我通過了值作爲用戶名=「用戶」和密碼=「通行證」,這在邏輯上是錯誤的。

回答

3

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

注視:= xlwhole爲我工作,節省了大量的時間。系統發生感謝您的幫助! –

+0

@ashishvb如果它適合您,請將答案標記爲工作解決方案。 – mielk

相關問題