如何使用正则表达式在Excel VBA中获取列号?

时间:2017-02-08 08:44:51

标签: excel vba excel-vba

我知道如何使用.Match,.Find和迭代(yuck)返回列号。

是否可以使用正则表达式更快地完成它?

1 个答案:

答案 0 :(得分:1)

尝试Debug.Print Cells(5,7).Column,它会输出7

以下是.Find方法的示例,并且 输出找到的单元格的列!

Sub test_Eswemenasja()
Dim FirstAddress As String, cF As Range, SearchedStr as String
SearchedStr = "Cat"

ActiveSheet.Range("A1").Activate
With ActiveSheet.Cells
    'First, define properly the Find method
    Set cF = .Find(What:=SearchedStr, _
                After:=ActiveCell, _
                LookIn:=xlFormulas, _
                LookAt:=xlPart, _
                SearchOrder:=xlByColumns, _
                SearchDirection:=xlNext, _
                MatchCase:=False, _
                SearchFormat:=False)

    'If there is a result, keep looking with FindNext method
    If Not cF Is Nothing Then
        FirstAddress = cF.Address
        Do
            'Message with the column number!
            MsgBox "Found in column : " & cF.column
            Set cF = .FindNext(cF)
        'Look until you find again the first result
        Loop While Not cF Is Nothing And cF.Address <> FirstAddress
    End If
End With

End Sub