본문 바로가기

엑셀

엑셀 셀에 있는 문장 단어로 여러 셀에 나누기, 여러 셀에 있는 단어들 한 셀에 문장으로 합치기(문자열 나누기, 합치기)

728x90

엑셀을 사용하다 보면 셀에 있는 문자열을 나누거나 합치는 것이 필요 할 때가 있습니다. 그 때 사용 할 수 있는 매크로로 txtSplit 과 txtJoin 라고 명명한 함수를 소개하겠습니다.

간만에 윤동주 님의 아름다운 시, 윤동주님의 서시를 감상해보겠습니다!

 

문장을 단어로 나누기

'서시' 한 문장이 각 셀마다 아래와 같이 들어 있다고 하면, txtSplit 함수를 실행하면 문장을 공백(스페이스)로 구분하여 각각의 셀에 입력 됩니다.

[사용법] 셀 선택 후 txtSplit 매크로 실행

Sub txtSplit()
' 문자열을 공백(Space)로 분할.
' 선택한(액티브 된) 셀.
Dim strings As Variant            ' 문자열을 배열로 지정
Dim c As Integer                ' 문자열의 카운터

    '빈셀이 있어도 진행.
    Do Until ActiveCell.Value = vbNullString

        strings = Split(ActiveCell.Value, Space(1))

        ' Write each found name part into a seperate column.
        For c = LBound(strings ) To UBound(strings )

            ' Extract element to an offset of active cell.
            ActiveCell.Offset(0, c + 1).Value = strings (c)
        Next

        ActiveCell.Offset(1, 0).Select  ' 다음열로 이동.
        DoEvents                        ' 큰 수가 나왔을때 프리즈 되는 것 방지.
    Loop
End Sub

 

단어들을 문장으로 합치기

[사용법] =txtJoin(" ", 1, C5:G5) ' txtJoin(Delimiter, True or False, Range)

Option Explicit

Function txtJoin(delimiter As String, ignore_empty As Boolean, text_range As Range) As String

Application.Volatile
Dim c As Range
Dim n As Long
n = 0
For Each c In text_range
 If ignore_empty = True Then
 If VBA.IsEmpty(c.Value) = False Then
 If n = 0 Then
 txtJoin = c.Value
 Else
 txtJoin = txtJoin & delimiter & c.Value
 End If
 n = n + 1
 End If
 
 Else
 
 If n = 0 Then
 txtJoin = c.Value
 Else
 txtJoin = txtJoin & delimiter & c.Value
 End If
 n = n + 1
 
 End If
Next

End Function

 

728x90