[VBA] 워크시트의 마지막 셀 주소 가져오기 (vba last row, vba last column, vba last cell address)

[VBA] 워크시트의 마지막 셀 주소 가져오기 (vba last row, vba last column, vba last cell address)

엑셀 VBA 마지막 셀 주소 가져오는 방법.

엑셀 VBA 마지막 행, 로우 가져오는 방법.

엑셀 VBA 마지막 열, 컬럼 가져오는 방법.

여러 코드가 있지만 시트 중간에 공백 셀이 존재하는 경우(ex : A1 셀이 공백) 공백을 문서의 끝으로 오인해서 잘못된 주소를 가져오는 경우가 많았다.

여태까지 이를 방지하기 위해서 공백이 10번 이상 연속되면 문서의 끝으로 판단하는 등 불완전한 방법을 사용해왔는데 아래 코드는 그런 문제가 없다.

Sub TestSub1()

Dim lastRow
Dim lastCol

lastRow = ActiveSheet.Cells.Find(“*”, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
lastCol = ActiveSheet.Cells.Find(“*”, LookIn:=xlFormulas, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

MsgBox (“lastRow : ” & lastRow) ‘lastRow : 75
MsgBox (“lastCol : ” & lastCol) ‘lastCol : 11

Dim lastCellAddr
lastCellAddr = ActiveSheet.Cells(lastRow, lastCol).Address

MsgBox (“lastCellAddr : ” & lastCellAddr) ‘$K$75

End Sub

참고사이트 : https://www.thespreadsheetguru.com/blog/2014/7/7/5-different-ways-to-find-the-last-row-or-last-column-using-vba