使用VBA在Excel中查找包含搜索字符串的单元格位置

时间:2015-01-11 20:53:17

标签: excel vba excel-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

问题: 请告诉我如何访问联系人和电话。请注意,可能会找到一个或多个条目。非常感谢!

3 个答案:

答案 0 :(得分:0)

您需要使用Offset对象的Range功能。这允许您使用单元格/范围作为起始位置来选择单元格。

所以在你的情况下

' 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

答案 1 :(得分:0)

您的代码中有两个主要问题区域。第二行不应该在最后添加.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

答案 2 :(得分:0)

  

如何实施搜索的一个例子

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