파이썬+VBA

엑셀VBA 문자열에서 숫자를 추출

E.X.I.T 2023. 6. 19. 14:09
728x90
반응형

Sub Get_number_in_string()
    Dim regex As Object
    Dim inputRange As Range
    Dim cell As Range
    Dim outputString As String
    
    ' Initialize regular expression object
    Set regex = CreateObject("VBScript.RegExp")
    
    ' Set the pattern to match numbers (\d+)
    regex.Pattern = "(\d{1,3},)*\d{3}"
    
    ' Select the range of cells
    Set inputRange = Selection ' Assumes you have already selected the desired range
    
    ' Loop through each cell in the selected range
    For Each cell In inputRange
        ' Extract numbers from the cell value
        If regex.test(cell.Value) Then
            Dim matches As Object
            Set matches = regex.Execute(cell.Value)
            
            ' Concatenate all matched numbers
            Dim i As Integer
            For i = 0 To matches.Count - 1
                outputString = matches.Item(i).Value
            Next i
        End If
        cell = outputString
    Next cell
End Sub

728x90
반응형