基于另一列中的子字符串检索列中的文本

时间:2012-07-16 08:53:08

标签: vba excel-vba excel-2007 substring excel

假设它在A2,A4,A5,A6中找到一些特定的文字,如“sa” 我需要分别在B2,B4,B5,B6中复制“sohail”, 像这样...

ImageName                   PhotographerName
pirf_20120523_sa0001.jpg    sohail
pirf_20120523_ml0001.jpg    manav
pirf_20120523_sa0001.jpg    sohail
pirf_20120523_sa0001.jpg    sohail
pirf_20120523_sa0001.jpg    sohail
pirf_20120529_sh0005.jpg    shirazi
pirf_20120523_ml0001.jpg    manav 
pirf_20120529_sh0005.jpg    shirazi

我试图检索它找到文本的地址......

Sub FindinTextInEachCell()

Dim rngX As Range


Set rngX = Worksheets("Sheet1").Range("A1:A10").Find("sa", lookat:=xlPart)
If Not rngX Is Nothing Then
    MsgBox "Found at " & rngX.Address
End If

End Sub

1 个答案:

答案 0 :(得分:0)

您没有正确使用Find方法,它只会返回它找到的第一个Range,您必须对后续范围使用findnext()方法,但是后续范围将重复,您必须将其与找到的第一个地址进行比较。

Sub foo()
On Error Resume Next

Dim rng As Range
Dim prng As Range
Dim firstAddress As String

With Worksheets(1).Range("A1:A10")
    Set rng = .Find("sa", LookIn:=xlValues, LookAt:=xlPart)
    If Not rng Is Nothing Then
        firstAddress = rng.Address
        Do
            Set prng = rng
            rng.Offset(0, 1) = "Sohail"
            Set rng = .FindNext(After:=prng)
        Loop While Not rng Is Nothing And rng.Address <> firstAddress
    End If
End With

End Sub