VBA CODE

VBA 빈행과 빈셀 A열 삭제하는 방법 코드

VBA 2023. 3. 31. 01:30

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