2013-02-18 29 views
22

我必須找到一個值celda在一個Excel工作表。我使用這個VBA代碼找到它:如何找到由VBA代碼的Excel列的值Cells.Find

Set cell = Cells.Find(What:=celda, After:=ActiveCell, LookIn:= _ 
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _ 
    xlNext, MatchCase:=False, SearchFormat:=False) 


If cell Is Nothing Then 
    'do it something 

Else 
    'do it another thing 
End If 

問題是,當我只有一個Excel列找到該值。我用下面的代碼找到它:

Columns("B:B").Select 
    Selection.Find(What:="VA22GU1", After:=ActiveCell, LookIn:=xlFormulas, _ 
     LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
     MatchCase:=False, SearchFormat:=False).Activate 

但我不知道如何使其適應第一VBA代碼,因爲我使用的值nothing

+6

http://www.siddharthrout.com/2011/07/14/find-and-findnext-in-excel-vba/也請避免使用'.Select'請參閱此鏈接HTTP: //stackoverflow.com/questions/10714251/excel-macro-avoiding-using-select/10718179#10718179 – 2013-02-18 08:07:05

+0

如果你只是想知道,如果該值範圍內的某處存在,它是更快的執行(值得的,如果檢查數百值)使用Excel公式。如果celda例如是一個數字,您可以使用IF評估( 「COUNTIF(工作表Sheet1!A1:A1000,」 &celda& 「)」)> 0 THEN ... – lessthanideal 2013-11-06 14:32:09

回答

32

只需使用

Columns("B:B").Select 
Set cell = Selection.Find(What:="celda", After:=ActiveCell, LookIn:=xlFormulas, _ 
     LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
     MatchCase:=False, SearchFormat:=False) 

If cell Is Nothing Then 
    'do it something 

Else 
    'do it another thing 
End If 
4

只是爲了完整起見,你也可以使用上面Excel表格相同的技術。

在下面的例子中,我期待在命名通常被設置爲隱藏Config中的表名爲「tblConfig」一個Excel表格中的任意單元格,將文本的。我接受Find方法的默認值。

Dim list As ListObject 
Dim config As Worksheet 
Dim cell as Range 


Set config = Sheets("Config") 
Set list = config.ListObjects("tblConfig") 

'search in any cell of the data range of excel table 
Set cell = list.DataBodyRange.Find(searchTerm) 

If cell Is Nothing Then 
    'when information is not found 
Else 
    'when information is found 
End If 
3
Dim strFirstAddress As String 
Dim searchlast As Range 
Dim search As Range 

Set search = ActiveSheet.Range("A1:A100") 
Set searchlast = search.Cells(search.Cells.Count) 

Set rngFindValue = ActiveSheet.Range("A1:A100").Find(Text, searchlast, xlValues) 
If Not rngFindValue Is Nothing Then 
    strFirstAddress = rngFindValue.Address 
    Do 
    Set rngFindValue = search.FindNext(rngFindValue) 
    Loop Until rngFindValue.Address = strFirstAddress