Excel - VBA

길이 0인 문자열 제거하기

EGTools 2023. 6. 28. 22:29
728x90

수식에서 IFERROR(수식, "") 처럼 결과를 길이가 0인 문자열로 설정한 경우나

이를 값으로 복사/붙여넣기 한 경우 값은 없지만 실제로는 빈셀이 아닌 경우에

이를 제거하도록 하는 매크로입니다.

 

 

수식이 있는 경우 제외하는 선택을 할 수 있습니다.

Sub RemoveZeroLengthString()
    Dim vData As Variant, vFormula As Variant, ExcludeFormula As Variant, iRow As Long, iCol As Long, r As Long, c As Long
    
    ExcludeFormula = MsgBox("수식이 들어 있는 셀은 제외할까요?", vbYesNoCancel)
    If ExcludeFormula = vbCancel Then Exit Sub
    ExcludeFormula = IIf(ExcludeFormula = vbYes, True, False)

    Application.ScreenUpdating = False
    Application.EnableEvents = False

    With ActiveSheet
        iRow = .UsedRange.Row + .UsedRange.Rows.Count - 1
        iCol = .UsedRange.Column + .UsedRange.Columns.Count - 1
        vData = .Range(.Cells(1, 1), .Cells(iRow, iCol)).Value2
        vFormula = .Range(.Cells(1, 1), .Cells(iRow, iCol)).Formula
    
        For r = 1 To UBound(vData, 1)
        For c = 1 To UBound(vData, 2)
            If Not IsEmpty(vData(r, c)) Then
              If vData(r, c) = "" Then
                If vFormula(r, c) = "" Then
                    .Cells(r, c) = Empty
                Else
                    If Not ExcludeFormula Then
                      If .Cells(r, c).HasArray Then
                        .Cells(r, c).FormulaArray = ""
                      Else
                        .Cells(r, c).Formula = ""
                      End If
                    End If
                End If
              End If
            End If
        Next c
        Next r
    End With
    MsgBox "길이가 0인 문자열을 모두 정리했습니다."
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    
End Sub
728x90