[英]Find cell position containing search string in Excel using VBA
這是查找表:
city contact person phone
San Francisco Peter Foo 123
San Francisco Steve Foo 321
New York Max Foo 456
我正在嘗試使用VBA查找聯系人的詳細信息:
city = Sheets("General User Information").Cells(14, 2).Value
Set cx = Sheets("Cities").Columns(1).Select
Set cy.Find(city)
If Not cy Is Nothing Then
'here I need to access the contact person and phone but unfortunately
'fail with various errors (i.e. object required, run time error, etc)
cyFirst = cy.Address
Do
'do something
Set cy = cx.FindNext(cy)
Loop Until cy.Address = cyFirst
End If
問題 :請告訴我如何訪問聯系人和電話。 請注意,可能會找到一個或多個條目。 非常感謝!
您需要使用Range
對象的Offset
功能。 這使您可以使用一個單元格/范圍作為開始位置來選擇一個單元格。
所以你的情況
' Range.Offset(rows, columns)
Debug.print "City: " & cy.Value2
' Read the cell one column to the right of cy
Debug.print "Contact Person:" & cy.Offset(0,1).Value2
' Read the cell two columns to the right of cy
Debug.print "Phone: " & cy.Offset(0,2).Value2
您的代碼中有兩個主要的問題區域。 第二行不應在末尾附加.Select
。
Set cx = Sheets("Cities").Columns(1)
第三行應該嘗試將cy設置為cx內的值。
Set cy = cx.Find(city)
放在一起,
Dim city As String, cyFirst As String, cx As Range, cy As Range
city = Sheets("General User Information").Cells(14, 2).Value
Set cx = Sheets("Cities").Columns(1)
Set cy = cx.Find(city)
If Not cy Is Nothing Then
cyFirst = cy.Address
Do
With Sheets("General User Information")
'do something
'do something
End With
Set cy = cx.FindNext(cy)
Loop Until cy.Address = cyFirst
End If
示例之一,如何實現搜索
Sub test()
Dim sSearchCriteriaCity$, oCell As Range, i&, x&
i = 0: x = Cells(Rows.Count, 1).End(xlUp).Row
' search criteria goes into inputbox
' it is better to use the user form for several criterias of searching
sSearchCriteriaCity = UCase(InputBox("Provide Search Criteria"))
If sSearchCriteriaCity = "" Then GoTo exitsub 'Exit if criteria was not provided
For Each oCell In ActiveSheet.Range("A2:A" & x) 'Column with city
If UCase(oCell.Value) Like "*" & sSearchCriteriaCity & "*" Then
oCell.Interior.Color = vbRed ' color cell with red
i = i + 1
Else
oCell.Interior.Color = xlNone ' remove color from cell
End If
Next
If i = 0 Then
MsgBox "Data matched with search criteria was not found!"
ElseIf i > 1 Then
MsgBox "Matched, " & i & " records found!"
End If
Exit Sub
exitsub:
MsgBox "Criteria was not provided!"
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.