programing

Microsoft Excel의 인셀과 루프 모두에서 정규 표현(Regex)을 사용하는 방법

javamemo 2023. 3. 6. 20:37
반응형

Microsoft Excel의 인셀과 루프 모두에서 정규 표현(Regex)을 사용하는 방법

Excel의 정규 표현을 사용하여 Excel의 강력한 그리드 같은 데이터 조작 설정을 활용하는 방법은 무엇입니까?

  • 문자열에 일치하는 패턴 또는 대체된 값을 반환하는 In-cell 함수.
  • Sub: 데이터 열을 루프하여 인접 셀에 일치하는 항목을 추출합니다.
  • 어떤 설정이 필요합니까?
  • Excel의 정규 표현 특수 문자는 무엇입니까?

Regex는 엑셀을 사용할 수 있기 때문에 많은 상황(정규 표현 사용 여부)에 이상적이지 않은 것으로 알고 있습니다.Left,Mid,Right,Instr유사한 조작에 대한 명령어를 입력합니다.

정규 표현은 패턴 매칭에 사용됩니다.

Excel에서 사용하는 절차는 다음과 같습니다.

순서 1: 「Microsoft VBScript Regular Expressions 5.5」에 VBA 레퍼런스 추가

  • 개발자 탭을 선택합니다(이 탭이 없습니다).
  • '코드' 리본 섹션에서 'Visual Basic' 아이콘을 선택합니다.
  • "Microsoft Visual Basic for Applications" 창의 상단 메뉴에서 "Tools"를 선택합니다.
  • "참조"를 선택합니다.
  • 워크북에 포함할 "Microsoft VBScript Regular Expressions 5.5" 옆에 있는 상자를 선택합니다.
  • [확인] 을 클릭합니다.

순서 2: 패턴의 정의

기본 정의:

-

  • a-z에서 za까지의합니다.
  • 0-5는 0 ~ ~5 의 합니다.

[]이 괄호 안에 있는 오브젝트 중 하나를 정확히 일치시킵니다.

  • [a]
  • [abc]는, a, , 또는 ca 의 1 하고 있습니다.b 는 a, b, ca, b, ca 입니다.
  • [a-z]는 알파벳의 단일 소문자와 일치합니다.

()반환을 위해 서로 다른 일치 항목을 그룹화합니다.아래의 예를 참조해 주세요.

{}이전에 정의된 패턴의 반복 복사본을 위한 승수입니다.

  • [a]{2}와 합니다.「 2 」 。aa
  • [a]{1,3}는 최소 합니다.a,aa,aaa

+앞에 정의된 패턴 중 적어도1개 또는 여러 개를 일치시킵니다.

  • a+a,aa,aaa »

?전에 중 시킵니다.

  • 예: 패턴이 존재하거나 존재하지 않을 수 있지만 한 번만 일치시킬 수 있습니다.
  • [a-z]?빈 문자열 또는 단일 소문자와 일치합니다.

*0으로 하다

  • 예: 존재하거나 존재하지 않을 수 있는 패턴에 대한 와일드카드.
  • [a-z]*빈 문자열 또는 소문자 문자열과 일치합니다.

. 이외의 의 문자와 합니다.\n

  • a.하여 "2" 이외의 의 문자열과 합니다.\n

|OR ★★★

  • a|b는 둘 중 하나입니다.a ★★★★★★★★★★★★★★★★★」b일치시킬 수 있습니다.
  • red|white|orange색상과 정확히 일치합니다.

^없음

  • [^0-9]할 수 .
  • [^aA]일 수 .a ('')A

\이어지는 특수 문자를 이스케이프합니다(위의 동작보다 우선함).

  • \.,\\,\(,\?,\$,\^

고정 패턴:

^ 시 .

  • ^a로 해야 .a
  • ^[0-9]첫 번째 문자는 숫자여야 합니다.

$ 끝에 .

  • a$.a

우선순위 테이블:

Order  Name                Representation
1      Parentheses         ( )
2      Multipliers         ? + * {m,n} {m, n}?
3      Sequence & Anchors  abc ^ $
4      Alternation         |

사전 정의된 문자 약어:

abr    same as       meaning
\d     [0-9]         Any single digit
\D     [^0-9]        Any single character that's not a digit
\w     [a-zA-Z0-9_]  Any word character
\W     [^a-zA-Z0-9_] Any non-word character
\s     [ \r\t\n\f]   Any space character
\S     [^ \r\t\n\f]  Any non-space character
\n     [\n]          New line

1: 매크로로 실행

에서는 셀의 .A1첫 번째 1글자나 두 글자가 숫자인지 확인합니다.이 경우 해당 문자열이 삭제되고 나머지 문자열이 표시됩니다.일치하지 않으면 일치하는 항목이 없음을 나타내는 상자가 나타납니다.A1「」의 값12abcabc의 값 , 。1abcabc의 값 , 。abc123숫자가 문자열의 시작 부분에 없었기 때문에 "Not Matched"가 반환됩니다.

Private Sub simpleRegex()
    Dim strPattern As String: strPattern = "^[0-9]{1,2}"
    Dim strReplace As String: strReplace = ""
    Dim regEx As New RegExp
    Dim strInput As String
    Dim Myrange As Range
    
    Set Myrange = ActiveSheet.Range("A1")
    
    If strPattern <> "" Then
        strInput = Myrange.Value
        
        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With
        
        If regEx.Test(strInput) Then
            MsgBox (regEx.Replace(strInput, strReplace))
        Else
            MsgBox ("Not matched")
        End If
    End If
End Sub

2: 내 함수로 실행

이 예는 예 1과 동일하지만 셀 내 함수로 실행되도록 설정되어 있습니다.사용하려면 코드를 다음과 같이 변경합니다.

Function simpleCellRegex(Myrange As Range) As String
    Dim regEx As New RegExp
    Dim strPattern As String
    Dim strInput As String
    Dim strReplace As String
    Dim strOutput As String
    
    
    strPattern = "^[0-9]{1,3}"
    
    If strPattern <> "" Then
        strInput = Myrange.Value
        strReplace = ""
        
        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With
        
        If regEx.test(strInput) Then
            simpleCellRegex = regEx.Replace(strInput, strReplace)
        Else
            simpleCellRegex = "Not matched"
        End If
    End If
End Function

을 셀에 .A1 공식을 입력해 주세요.=simpleCellRegex(A1)B1이렇게 '어울리지 않다'라고 합니다.

결과 이미지


3: 루프 스루 범위

이 예는 예 1과 동일하지만 셀 범위를 루프합니다.

Private Sub simpleRegex()
    Dim strPattern As String: strPattern = "^[0-9]{1,2}"
    Dim strReplace As String: strReplace = ""
    Dim regEx As New RegExp
    Dim strInput As String
    Dim Myrange As Range
    
    Set Myrange = ActiveSheet.Range("A1:A5")
    
    For Each cell In Myrange
        If strPattern <> "" Then
            strInput = cell.Value
            
            With regEx
                .Global = True
                .MultiLine = True
                .IgnoreCase = False
                .Pattern = strPattern
            End With
            
            If regEx.Test(strInput) Then
                MsgBox (regEx.Replace(strInput, strReplace))
            Else
                MsgBox ("Not matched")
            End If
        End If
    Next
End Sub

4: 다른 패턴의 분할

( 「 」, 「 」, 「 」)를 루프 하고 있습니다.A1,A2&A3)는 3 에 1 4 합니다.()$1는 첫 번째 하는 첫 .().

Private Sub splitUpRegexPattern()
    Dim regEx As New RegExp
    Dim strPattern As String
    Dim strInput As String
    Dim Myrange As Range
    
    Set Myrange = ActiveSheet.Range("A1:A3")
    
    For Each C In Myrange
        strPattern = "(^[0-9]{3})([a-zA-Z])([0-9]{4})"
        
        If strPattern <> "" Then
            strInput = C.Value
            
            With regEx
                .Global = True
                .MultiLine = True
                .IgnoreCase = False
                .Pattern = strPattern
            End With
            
            If regEx.test(strInput) Then
                C.Offset(0, 1) = regEx.Replace(strInput, "$1")
                C.Offset(0, 2) = regEx.Replace(strInput, "$2")
                C.Offset(0, 3) = regEx.Replace(strInput, "$3")
            Else
                C.Offset(0, 1) = "(Not matched)"
            End If
        End If
    Next
End Sub

결과:

결과 이미지


기타 패턴 예시

String   Regex Pattern                  Explanation
a1aaa    [a-zA-Z][0-9][a-zA-Z]{3}       Single alpha, single digit, three alpha characters
a1aaa    [a-zA-Z]?[0-9][a-zA-Z]{3}      May or may not have preceding alpha character
a1aaa    [a-zA-Z][0-9][a-zA-Z]{0,3}     Single alpha, single digit, 0 to 3 alpha characters
a1aaa    [a-zA-Z][0-9][a-zA-Z]*         Single alpha, single digit, followed by any number of alpha characters

</i8>    \<\/[a-zA-Z][0-9]\>            Exact non-word character except any single alpha followed by any single digit

Excel 공식에서 직접 정규 표현을 사용하려면 다음 UDF(사용자 정의 함수)가 도움이 됩니다.엑셀 함수로서 정규 표현 기능을 어느 정도 직접 공개합니다.

구조

2~3개의 파라미터가 필요합니다.

  1. 정규식을 사용할 텍스트입니다.
  2. 정규 표현.
  3. 결과 표시 방법을 지정하는 형식 문자열입니다.함할 it it it it it it it it it it it it it를 할 수 .$0,$1,$2기타 등등. $0경기입니다.$1및 up은 정규 표현 내의 각 일치 그룹에 대응합니다.은 "" 입니다.$0.

몇 가지 예

이메일 주소 추출:

=regex("Peter Gordon: some@email.com, 47", "\w+@\w+\.\w+")
=regex("Peter Gordon: some@email.com, 47", "\w+@\w+\.\w+", "$0")

★★★★★★some@email.com

여러 개의 서브스트링 추출:

=regex("Peter Gordon: some@email.com, 47", "^(.+): (.+), (\d+)$", "E-Mail: $2, Name: $1")

★★★★★★E-Mail: some@email.com, Name: Peter Gordon

단일 셀의 결합된 문자열을 여러 셀의 해당 구성요소로 분해하려면 다음 절차를 수행합니다.

=regex("Peter Gordon: some@email.com, 47", "^(.+): (.+), (\d+)$", "$" & 1)
=regex("Peter Gordon: some@email.com, 47", "^(.+): (.+), (\d+)$", "$" & 2)

★★★★★★Peter Gordon some@email.com

사용방법

이 UDF 를 사용하려면 , 다음의 순서를 실행합니다(대략, 이 Microsoft 페이지에 근거합니다).거기에 좋은 추가 정보가 있습니다!)

  1. 파일에서 Excel('xlsm')을 누릅니다.ALT+F11Microsoft Visual Basic for Applications Editor를 엽니다.
  2. 정규 표현 라이브러리에 VBA 참조를 추가합니다(Portland Runners++ answer에서 부끄럽지 않게 복사).
    1. [툴(Tools)]-> [참조(References)]를 클릭합니다(독일어 스크린샷을 양해 바랍니다).도구 -> 레퍼런스
    2. 목록에서 Microsoft VBScript Regular Expressions 5.5를 찾아 옆에 있는 체크박스를 켭니다.
    3. [확인] 을 클릭합니다.
  3. [모듈 삽입]을 클릭합니다.모듈에 다른 이름을 붙일 경우 모듈의 이름이 아래 UDF와 동일하지 않은지 확인하십시오(예: 모듈 이름 지정).Regex ★★★★★★regex#NAME! 에러가 발생합니다).

    아이콘 행의 두 번째 아이콘 -> 모듈

  4. 가운데 큰 텍스트창에 다음 내용을 삽입합니다.

    Function regex(strInput As String, matchPattern As String, Optional ByVal outputPattern As String = "$0") As Variant
        Dim inputRegexObj As New VBScript_RegExp_55.RegExp, outputRegexObj As New VBScript_RegExp_55.RegExp, outReplaceRegexObj As New VBScript_RegExp_55.RegExp
        Dim inputMatches As Object, replaceMatches As Object, replaceMatch As Object
        Dim replaceNumber As Integer
    
        With inputRegexObj
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = matchPattern
        End With
        With outputRegexObj
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = "\$(\d+)"
        End With
        With outReplaceRegexObj
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
        End With
    
        Set inputMatches = inputRegexObj.Execute(strInput)
        If inputMatches.Count = 0 Then
            regex = False
        Else
            Set replaceMatches = outputRegexObj.Execute(outputPattern)
            For Each replaceMatch In replaceMatches
                replaceNumber = replaceMatch.SubMatches(0)
                outReplaceRegexObj.Pattern = "\$" & replaceNumber
    
                If replaceNumber = 0 Then
                    outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).Value)
                Else
                    If replaceNumber > inputMatches(0).SubMatches.Count Then
                        'regex = "A to high $ tag found. Largest allowed is $" & inputMatches(0).SubMatches.Count & "."
                        regex = CVErr(xlErrValue)
                        Exit Function
                    Else
                        outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).SubMatches(replaceNumber - 1))
                    End If
                End If
            Next
            regex = outputPattern
        End If
    End Function
    
  5. Microsoft Visual Basic for Applications Editor 창을 저장하고 닫습니다.

급하신 분들을 위해 팥짐답변을 확대합니다.

  1. Excel 워크북을 엽니다.
  2. Alt+F11 VBA/Macros 창을 엽니다.
  3. [툴(Tools)]아래 [참조(References)]에서 regex에 참조를 추가합니다.
    ![Excel VBA 폼 참조 추가
  4. Microsoft VBScript Regular Expression 5.5 선택
    ![Excel VBA regex 참조 추가
  5. 새 모듈을 삽입합니다(코드가 모듈에 있어야 하며 그렇지 않으면 작동하지 않습니다).
    ![Excel VBA 삽입 코드 모듈
  6. 에서는, 「」가 사용되고 있습니다.
    ![Excel VBA 코드를 모듈에 삽입합니다.
  7. 다음 코드를 추가합니다.

    Function RegxFunc(strInput As String, regexPattern As String) As String
        Dim regEx As New RegExp
        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .pattern = regexPattern
        End With
    
        If regEx.Test(strInput) Then
            Set matches = regEx.Execute(strInput)
            RegxFunc = matches(0).Value
        Else
            RegxFunc = "not matched"
        End If
    End Function
    
  8. regex 패턴은 셀 중 하나에 배치되어 절대 참조가 사용됩니다.![Excel regex 함수의 셀 내 사용방법 함수는 작성된 워크북에 연결됩니다.
    다른 워크북에서 사용할 필요가 있는 경우 기능을 Personal에 저장합니다.XLSB

제 시도는 다음과 같습니다.

Function RegParse(ByVal pattern As String, ByVal html As String)
    Dim regex   As RegExp
    Set regex = New RegExp
    
    With regex
        .IgnoreCase = True  'ignoring cases while regex engine performs the search.
        .pattern = pattern  'declaring regex pattern.
        .Global = False     'restricting regex to find only first match.
        
        If .Test(html) Then         'Testing if the pattern matches or not
            mStr = .Execute(html)(0)        '.Execute(html)(0) will provide the String which matches with Regex
            RegParse = .Replace(mStr, "$1") '.Replace function will replace the String with whatever is in the first set of braces - $1.
        Else
            RegParse = "#N/A"
        End If 
    End With
End Function

이는 직접적인 답변은 아니지만 보다 효율적인 대안을 제시할 수 있습니다.Google Sheets에는 Regex Functions가 여러 개 내장되어 있어 매우 편리하고 Excel의 일부 기술 절차를 회피할 수 있습니다.PC에서 Excel을 사용하는 것에는 몇 가지 이점이 있지만, 대부분의 사용자에게 Google Sheets는 동일한 경험을 제공하며 휴대성과 문서 공유에 있어 몇 가지 이점을 제공할 수 있습니다.

제공하다

REGEXEXTRACT: 정규식에 따라 일치하는 하위 문자열을 추출합니다.

REGEXREPLACE: 정규 표현을 사용하여 텍스트 문자열의 일부를 다른 텍스트 문자열로 바꿉니다.

대체: 문자열의 기존 텍스트를 새 텍스트로 바꿉니다.

바꾸기: 텍스트 문자열의 일부를 다른 텍스트 문자열로 바꿉니다.

이런 셀에 직접 입력할 수 있고 원하는 것은 무엇이든 만들 수 있습니다.

=REGEXMATCH(A2, "[0-9]+")

또한 다음과 같은 IF 문과 같은 다른 함수와 함께 매우 잘 작동합니다.

=IF(REGEXMATCH(E8,"MiB"),REGEXEXTRACT(E8,"\d*\.\d*|\d*")/1000,IF(REGEXMATCH(E8,"GiB"),REGEXEXTRACT(E8,"\d*\.\d*|\d*"),"")

여기에 이미지 설명 입력

Excel의 VBS 컴포넌트에 위축된 사용자에게 간단한 회피책이 제공되기를 바랍니다.

귀중한 컨텐츠에 덧붙여, VBA내의 RegEx가 이상적이지 않은 이유에 대해 상기시켜 드립니다.되는 것은 "" " " " " " " " " 를 수 .Error 5017(나는 나의 희생자이다)작가의 추측을 남길지도 모른다.

지원되는 항목에 대해 몇 가지 소스를 찾을 수 있지만 지원되지 않는 메타 문자 등을 알아두면 도움이 됩니다.자세한 설명은 이쪽에서 확인할 수 있습니다.이 소스에 기재되어 있습니다.

"VBScript 정규 표현은...버전 5.5 에서는 이전 버전의 VBScript에서는 볼 수 없었던 몇 가지 필수 regex 기능이 구현되어 있습니다.JavaScript 및 VBScript는 Perl 스타일의 정규 표현을 구현합니다.그러나 Perl 및 기타 최신 정규 표현 플레이버에서 사용할 수 있는 고급 기능이 많이 부족합니다.


지원되지 않는 것은 다음과 같습니다.

  • String ancor의 \A 을 합니다.^ in 첫 전에 position을 매칭합니다.
  • String (스트링 종료)\Z 을 합니다.$문자열의 마지막 문자 뒤에 있는 표현과 일치하는 달러 기호
  • 긍정적인 뒷모습. §:(?<=a)b(포즈드 룩)전방에 대응)
  • LookBehind(뒤를 참조). §:(?<!a)b(부정적인 표정)전방에 대응)
  • 아토믹 그룹화
  • 소유 수량화자
  • [ ] :\{uFFFF}
  • 명명된 캡처 그룹.또는 번호부 캡처 그룹 사용
  • 인라인 수식자. §:/i 구분) (대소문자 구분)/g ) ( (( ) 설정에서는, 「 」를 참조해 .RegExp properties > " 속성" >RegExp.Global = True ★★★★★★★★★★★★★★★★★」RegExp.IgnoreCase = True가능한 경우.
  • 조건
  • 정규 표현 코멘트이것들을 일반과 함께 추가'에서의

나는 이미 VBA 내의 정규 표현을 사용하여 여러 번 벽에 부딪쳤다. 통상 usually usually usually usually usually LookBehind가끔 수식어도 까먹어요.저는 위에서 언급한 모든 배경들을 직접 경험하지는 못했지만, 좀 더 상세한 정보를 참고하면서 좀 더 자세히 알아보려고 노력했습니다.자유롭게 코멘트/수정/추가해 주세요.regular-expressions.info에 많은 정보를 요청하십시오.

추신: 일반적인 VBA 방법 및 기능을 언급하셨는데, RegEx가 실패할 경우 그 방법(적어도 제 자신에게는)이 도움이 되었음을 확인할 수 있습니다.

이걸 세포기능으로 사용할 필요가 있었어요SUM ★★★★★★★★★★★★★★★★★」VLOOKUP

  1. 매크로가 유효한 Excel 파일(xlsm으로 저장)에 있는지 확인합니다.
  2. 개발자 도구 열기 +
  3. 다른 답변과 마찬가지로 Microsoft VBScript Regular Expression 5.5 추가
  4. 워크북 또는 자체 모듈에서 다음 기능을 생성합니다.

    Function REGPLACE(myRange As Range, matchPattern As String, outputPattern As String) As Variant
        Dim regex As New VBScript_RegExp_55.RegExp
        Dim strInput As String
    
        strInput = myRange.Value
    
        With regex
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = matchPattern
        End With
    
        REGPLACE = regex.Replace(strInput, outputPattern)
    
    End Function
    
  5. 에서 '아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, =REGPLACE(B1, "(\w) (\d+)", "$1$2") " ~ "

, 여기 ㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇ.regex_subst()§:

=regex_subst("watermellon", "[aeiou]", "")
---> wtrmlln
=regex_subst("watermellon", "[^aeiou]", "")
---> aeeo

여기 간단한 코드가 있습니다(어쨌든 저에겐 더 간단한 코드입니다).예를 들어 위의 출력 패턴을 사용하여 적절한 출력 패턴을 작성하는 방법을 찾을 수 없었습니다.

Function regex_subst( _
     strInput As String _
   , matchPattern As String _
   , Optional ByVal replacePattern As String = "" _
) As Variant
    Dim inputRegexObj As New VBScript_RegExp_55.RegExp

    With inputRegexObj
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = matchPattern
    End With

    regex_subst = inputRegexObj.Replace(strInput, replacePattern)
End Function

스크립트를 이식할 수 있어야 하므로 참조 라이브러리를 활성화할 필요가 없습니다.Dim foo As New VBScript_RegExp_55.RegExp이 원인이 되어 「」가 되었다.User Defined Type Not Defined하지만 제게 맞는 해결책을 찾았어요

@chrisneilsen을 사용하여 RE 코멘트를 갱신합니다.

레퍼런스 라이브러리를 유효하게 하는 것은 로컬 컴퓨터 설정과 관련되어 있다고 생각했지만, 실제로는 워크북과 직접 관련되어 있습니다.따라서 참조 라이브러리를 활성화하고 매크로 지원 워크북을 공유할 수 있으므로 최종 사용자가 라이브러리를 활성화할 필요가 없습니다.경고:Late Binding의 장점은 개발자가 사용자의 컴퓨터에 잘못된 버전의 오브젝트 라이브러리가 설치되는 것을 걱정할 필요가 없다는 것입니다.이 문제는 아마 의 문제가 되지 않을 것입니다.VBScript_RegExp_55.RegExp라이브러리입니다만, 「퍼포먼스」벤티지라고 하는 것은, 현시점에서는 가치 있는 것은 아닙니다.내 코드로 밀리초라고 하는 것을 알 수 없기 때문입니다.나는 이것이 다른 사람들이 이해할 수 있도록 업데이트 할 가치가 있다고 느꼈다.레퍼런스 라이브러리를 유효하게 하면, 「얼리 바인드」를 사용할 수 있습니다만, 그렇지 않은 경우는 코드는 정상적으로 동작합니다만, 퍼포먼스나 디버깅 기능에 대해서는 「레이트 바인드를 실시해, 느슨하게 할 필요가 있습니다.

출처 : https://peltiertech.com/Excel/EarlyLateBinding.html

이 하고 것은 셀에 입니다.A1해 보세요.strPattern잘 해 주세요, 조정해 주세요.rng원하는 대로

Public Sub RegExSearch()
'https://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops
'https://wellsr.com/vba/2018/excel/vba-regex-regular-expressions-guide/
'https://www.vitoshacademy.com/vba-regex-in-excel/
    Dim regexp As Object
    'Dim regex As New VBScript_RegExp_55.regexp 'Caused "User Defined Type Not Defined" Error
    Dim rng As Range, rcell As Range
    Dim strInput As String, strPattern As String
    
    Set regexp = CreateObject("vbscript.regexp")
    Set rng = ActiveSheet.Range("A1:A1")
        
    strPattern = "([a-z]{2})([0-9]{8})"
    'Search for 2 Letters then 8 Digits Eg: XY12345678 = Matched

    With regexp
        .Global = False
        .MultiLine = False
        .ignoreCase = True
        .Pattern = strPattern
    End With

    For Each rcell In rng.Cells

        If strPattern <> "" Then
            strInput = rcell.Value

            If regexp.test(strInput) Then
                MsgBox rcell & " Matched in Cell " & rcell.Address
            Else
                MsgBox "No Matches!"
            End If
        End If
    Next
End Sub

언급URL : https://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops

반응형