Code :
Sub MyColumnSelect()
Dim myCurrentRow As Long
Dim myLastColumn As Long
myCurrentRow = ActiveCell.Row
myLastColumn = ActiveCell.SpecialCells(xlLastCell).Column
Range(ActiveCell, Cells(myCurrentRow, myLastColumn)).Select
End Sub
I need to extend my selection from any colum or any row to the last used column in the sheet. This code extends the selection to a particular column, in my case to column P
. I don't know why is this the case but even if there are only 4 columns, it still extends the selection to column P
.
PS: I know I shouldn't use select
, but I can't make it work even with select
. Need Help.
Bit of googling would have absolutely yielded an answer. This is the most common way of retrieving the last actively used row
Shets("Sheetname").Cells(Rows.Count, <inColumn>).End(xlUp).Row
and column
Shets("Sheetname").Cells(<inRow>, Columns.Count).End(xlToLeft).Column
In your case, presuming your sheet is named " Sheet1
" it would be:
Dim lr as Long
Dim lc as Long
lr = Sheets("Sheet1").Cells(Rows.Count, 2).End(xlUp).Row
lc = Sheets("Sheet1").Cells(4, Columns.Count).End(xlToLeft).Column
Obviously, if your column ranges vary, you should retrieve them in a loop (eg. loop through all the active rows)
For i = 3 to lr
lc = Sheets("Sheet1").Cells(i, Columns.Count).End(xlToLeft).Column
' do something
Next i
Also, do absolutely read up on why you should not use Select
, ActiveSheet
and so on..
Try this:
Sub MyColumnSelect()
Dim myRow, myLastColumn As Long
For myRow = 3 To ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row
myLastColumn = ActiveSheet.Cells(myRow, Columns.Count).End(xlToLeft).Column
ActiveSheet.Range(Cells(myRow, 1), Cells(myRow, myLastColumn)).Copy
Next
End Sub
Ron de Bruin - Find last row, column or last cell show you how to find the last used column.
Sub MyColumnSelect()
Dim myCurrentRow As Long
Dim myLastColumn As Long
myCurrentRow = ActiveCell.Row
myLastColumn = Cells.Find(What:="*", After:=Cells(1, 1), _
Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, MatchCase:=False).Column
Range(ActiveCell, Cells(myCurrentRow, myLastColumn)).Select
End Sub
This also works. But beware that UsedRange
can sometimes extend past the data do to non-continuous formatting.
Intersect(ActiveCell.EntireRow, ActiveSheet.UsedRange).Select
As @Rawrplus pointed out using ActiveCell
and Selection
are bad habits and should be avoided. Watch: Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.