2016-04-04 116 views
0

我需要一个函数或其他函数来返回指定值的范围。按值查找范围Excel-VBA

我想通过指定的范围检查循环,如果每个单元格中的值等于我指定的值并构建一个范围。有没有更优雅的方法?

回答

0

这是我建立的功能。它返回找到所需值的联合范围:

Private Function FindRange(what As String, lookin As Range) As Range 

    Dim cell As Range 

    On Error GoTo errhandler 

    For Each cell In lookin.Cells 
     If UCase(cell.Value) = UCase(what) Then 

      If findrange Is Nothing Then 
       Set findrange = cell 
      Else 
       Set findrange = Application.Union(findrange, cell) 
      End If 

     End If 
    Next cell 

    Exit Function 

errhandler: 
    findrange = CVErr(xlErrNA) 

End Function 
0

请尝试下面的代码。您可以使用公式在单元格中获得结果。

=findvalueandrange(searchstring,selectyourrange) 

Public Function findvalueandrange(findingtext As String, r As Range) As String 
    Dim cell As Range 
    For Each cell In r.Cells 
     If LCase(cell.Value) = LCase(findingtext) Then 
      If findvalueandrange = "" Then 
       findvalueandrange = cell.Address & ":" & cell.Value 
      Else 
       findvalueandrange = findvalueandrange & "|" & cell.Address & ":" & cell.Value 
      End If 
     End If 
    Next cell 
End Function 

希望你满意?