VBA to count columns

chaddres

Board Regular
Joined
Jun 14, 2014
Messages
143
Office Version
  1. 365
Platform
  1. Windows
I have data in B1 that runs across the entire row, but the last column can vary. How do I count columns to find out the last column in B with data and then add 1 to it? So, if my last cell is Z2, I want to activate AA2 (so I can drop a formula in it). I know how to drop the formula in, I just do not know how to count columns. Here is what I tried.

VBA Code:
Sub TestSelect()
Dim lastcol As Long
lastcol = ActiveSheet.Cells(ActiveCell.Row, Application.Columns.Count).End(xlToLeft).Column
Range(lastcol & "2").Select
End Sub
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
Try this:
VBA Code:
Sub TestSelect()
Dim lastcol As Long
lastcol = Cells(2, Columns.Count).End(xlToLeft).Column
Cells(2, lastcol + 1).Select
End Sub
if you want it to work for row 2.

If you want it to work for the active row, then use:
VBA Code:
Sub TestSelect()
Dim lastcol As Long
lastcol = Cells(ActiveCell.Row, Columns.Count).End(xlToLeft).Column
Cells(ActiveCell.Row, lastcol + 1).Select
End Sub

Or more simply:
VBA Code:
Sub TestSelect()
Cells(2, Columns.Count).End(xlToLeft).Offset(0, 1).Select
End Sub
or
VBA Code:
Sub TestSelect()
Cells(ActiveCell.Row, Columns.Count).End(xlToLeft).Offset(0, 1).Select
End Sub
 
Upvote 0
Solution

Forum statistics

Threads
1,215,432
Messages
6,124,860
Members
449,194
Latest member
HellScout

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top