VBA Excel匹配或查找子字符串

时间:2013-08-30 10:24:59

标签: excel vba

快速举例:

    A      B       C      D      E      F
1          
2                 str1   str2   str3   str4

我想在第2行存储第一个范围对象,其中str为单元格的前三个字符。

这可以在VBA中使用吗?

这就是我想要实现的目标:

Dim rng As Range
Dim colNr as integer
colNr = WorksheetFunction.Match(left(cell.value,3)="str", .range("2:2"), 0)
set rng = Sheets("Sheet1").cells(2,colNr)

2 个答案:

答案 0 :(得分:0)

从根本上说,我会在第一次查找时使用For Each ... In ... Next循环和中断。这是一个没有太多错误检查的工作草案(TargetRange只有1行,TargetCell是一个字符串,UCase / LCase等等):

Function FirstMatch(TargetRange As Range, SearchString As String) As Variant
Dim TargetCell As Range

    ' if we don't find any, we return  a #N/A error value
    FirstMatch = CVErr(xlErrNA)

    For Each TargetCell In TargetRange.Cells
        If InStr(1, TargetCell, SearchString) Then
            ' returning the value of first find
            ' FirstMatch = TargetCell

            ' returning the column position relative to the first cell in selected range
            FirstMatch = TargetCell.Column - TargetRange(1, 1).Column + 1
            Exit Function
        End If
    Next TargetCell

End Function

您案件的用法是:

A2:=FirstMatch(C2:F2, "str")

根据您的需要修改If ...条件(例如Left(...)等)

使用一个功能可以避免硬编码(坏坏坏)!

谨慎提及:尽管For Each ... In ... Next doesn't guarantee a strictly sequential processing我总是觉得在使用中等大小的1维范围时相当安全。如果您想绝对确定需要引入索引变量并使用普通的For ... Next循环。

答案 1 :(得分:0)

你非常接近:

Dim rng As Range
Dim colNr as Long
With Sheets("Sheet1")
    colNr = WorksheetFunction.Match("str*", .range("2:2"), 0)
    set rng = .cells(2,colNr)
End With