The following code should do what you want. Note: I am not selecting anything since this slows things down to no advantage.
Dim ColLast as Long
Dim ValueColLast as String
Dim HeadColLast as String
With Sheets(xxxxx)
ColLast = .Cells(2,Columns.Count).End(xlToLeft).Column
ValueColLast = .Cells(2, ColLast).Value
HeadColLast = .Cells(1,ColLast).Value
End With
Cells(Row, Column)
addresses the cell identified by Row and Column in the active worksheet. Row must be a number. Column can be a number (eg 1 or 104) or a column identifier (eg "A" or "CZ")
.Cells(Row, Column)
addresses the cell identified by Row and Column in the worksheet identified in the With statement. Note the leading dot.
.Cells(2,Columns.Count)
addresses the last cell in row 2 since Columns.Count
given the number of columns per worksheet for the current version of Excel. `Rows.Count
does the same for rows.
Assuming .Cells(2,Columns.Count)
is blank, .Cells(2,Columns.Count).End(xlToLeft)
finds the next cell in the specified direction with a value. This is the VBA equivalent of Ctrl+LeftArrow. xlToRight
, xlUp
and xlDown
allow you to move in the other directions. .Cells(Rows.Count,"A").End(xlUp)
gives the last used row in Column A.
.Cells(2,Columns.Count).End(xlToLeft).Column
gives the number of the last used column in row 2.
ValueColLast = .Cells(2, ColLast).Value
sets ValueColLast to the value of the last cell in Row 2. I have defined ValueColLast as a String because, if I assumed it was a number and defined it as Long, I would get an error if it was not.
HeadColLast = .Cells(1,ColLast).Value
sets HeadColLast to value in Row 1.
Hope this all makes sense.