VBA Macro/VBA Excel

[엑셀] 빈 행, 빈셀 삭제하기 매크로

루아흐뉴마 2017. 11. 14. 20:21
반응형



매크로 설명


  • 첫 번째 시트 "A"열의 빈셀 또는 빈셀이 있는 행 전체를 삭제하는 매크로
  • 이 방법 외에도 SpecialCells 메서드로 빈행을 찾아서 없앨 수 있다. (방법은 많다.)
  • 많은 데이터가 아니거나 손이 많이 가지 않는다면, 자동필터를 이용해서 빈 필드는 제외하고 따로 복사하는 방법을 추천한다.


VBA Code 예시


Option Explicit
Sub empt_row_del()
Dim i As Long
Dim lastRow As Long
Dim targetCol As String
Dim mySheet As Worksheet

Set mySheet = Sheets(1) 'mySheet를 첫 번째 시트로 설정, 다른 시트가 필요하다면 변경
With mySheet.UsedRange
lastRow = .Row + .Rows.Count - 1 '마지막 셀 번호
End With
targetCol = "A" 'A열에 있는 빈행만 검색하도록 설정

For i = lastRow To 1 Step -1 '첫 행부터 시작하면 빈 셀을 삭제할 경우 인덱스가 꼬이기 때문에 마지막 행에서 거꾸로 와야 한다.
    If mySheet.Cells(i, targetCol) = "" Then '빈행이면
    'If trim(mysheet.Cells(i, targetcol)) = "" Then '셀에 스페이스바로 채워져 있어서 빈칸이지만 빈칸으로 안보이는 경우
        mySheet.Cells(i, targetCol).Delete shift:=xlUp '해당 셀 삭제 및 셀을 위쪽으로 밀기
        'mySheet.Cells(i, targetCol).EntireRow.Delete shift:=xlUp 셀이 아닌 행 전체 삭제 코드
    End If
Next i

MsgBox "COMPLETE"

End Sub



실행 결과




 Copyright (2018) Ruahneuma. All Rights Reserved.


반응형