在单元格中找到单词“ year”,并考虑单词前面的数字

时间:2018-10-16 17:48:36

标签: excel vba cell extract word

因此,我有一个包含年限的单元格列表,但是它们没有遵循特定的顺序,这意味着“ 1 Year”可能在开头,“ 6 Years”可能在结尾。 我使用下面的VBA来标识包含“年份”,“年份”,“ Yr”和“ Y”的所有单元格,但不确定如何提取之前的数字,我相信我需要将Celloffset 0,2(因为数字和术语“年”之间有一个空格),但不确定如何设置代码,不仅要找到单词,还要考虑单词之前的2位并放在其旁边的列中。

任何建议将不胜感激!

Sub Sample()
Dim MyAr(1 To 3) As String
Dim ws As Worksheet
Dim aCell As Range, bCell As Range
Dim i As Long

Set ws = ThisWorkbook.Sheets("Sheet1")

MyAr(1) = "year"
MyAr(2) = "years"
MyAr(3) = "Y"

With ws
    '~~> Loop through the array
    For i = LBound(MyAr) To UBound(MyAr)
        Set aCell = .Columns(1).Find(What:=MyAr(i), LookIn:=xlValues, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

        If Not aCell Is Nothing Then
            Set bCell = aCell
            aCell.Interior.ColorIndex = 3

            Do
                Set aCell = .Columns(1).FindNext(After:=aCell)

                If Not aCell Is Nothing Then
                    If aCell.Address = bCell.Address Then Exit Do
                    aCell.Interior.ColorIndex = 3
                Else
                    Exit Do
                End If
            Loop
        End If
    Next
End With
End Sub

0 个答案:

没有答案