2013-02-18 42 views
22

Tôi phải tìm một giá trị celda trong trang tính Excel. Tôi đã sử dụng mã VBA này để tìm này:Cách tìm giá trị trong cột excel bằng mã vba 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 

Vấn đề là khi tôi phải tìm giá trị chỉ trong một cột excel. Tôi tìm thấy mã tiếp theo:

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

Nhưng tôi không biết cách điều chỉnh mã vba đầu tiên vì tôi phải sử dụng giá trị nothing.

+6

http://www.siddharthrout.com/2011/07/14/find-and-findnext-in-excel-vba/ Cũng hãy tránh sử dụng '.Select' Xem liên kết này http: //stackoverflow.com/questions/10714251/excel-macro-avoiding-using-select/10718179#10718179 –

+0

Nếu bạn chỉ muốn biết liệu giá trị có tồn tại ở đâu đó trong phạm vi hay không, nó sẽ được thực hiện nhanh hơn (đáng giá nếu kiểm tra hàng trăm giá trị) để sử dụng công thức Excel. Nếu celda là một số ví dụ, bạn có thể sử dụng IF Đánh giá ("COUNTIF (Sheet1! A1: A1000," & celda & ")")> 0 THÌ ... – lessthanideal

Trả lời

32

Chỉ cần sử dụng

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

Chỉ vì lợi ích của sự hoàn chỉnh, bạn cũng có thể sử dụng kỹ thuật tương tự trên với bảng excel.

Trong ví dụ bên dưới, tôi đang tìm văn bản trong bất kỳ ô nào trong Bảng Excel có tên "tblConfig", đặt trong trang tính có tên Config thường được đặt thành ẩn. Tôi chấp nhận các giá trị mặc định của phương thức 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 
Các vấn đề liên quan