There are certain situations where we perform some tasks by finding last used Column with data in a Row. For examples, There may be 100 rows and each row may have the data in certain number of columns which ic not fixed in all the rows. In this situation we loop through the rows and need to find the last used column in each row and do what ever we need to do.
We can use count the number of columns using in the active sheet from there we can come back in particular row to get the exact column with data. We can use Column property to get last used Column .
The following example will show you how to find last column with data in a particular row. In this example we are finding the last used column in Row 1.
'In this example we are finding the last Columns of Row 1
Dim lastColumn As Integer
lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
- Open an excel workbook
- Press Alt+F11 to open VBA Editor
- Insert a New Module from Insert Menu
- Copy the above code and Paste in the code window
- To check, enter some data in a first row at E1
- Now Run a Macro, you should see a message box with result 5
Here is the example data and screen-shot with output.
The following example will show you real time example and when need find the last column with data in each row.
- User wants to paste his data for 5 Departments
- Number of items in each row could be any thing between 1 to 15 (it is not fixed in all the rows)
- Find maxim sales from 5 departments and Bold the Font
Dim lastColumn, lCol As Integer
Dim iCntr, jCntr, iMaxCol As Integer
For iCntr = 1 To 5
vMax = 0
iMaxCol = 2
'Finding last row of current row
lastColumn = .Cells(iCntr, .Columns.Count).End(xlToLeft).Column
lCol = lastColumn
Range(Cells(iCntr, 2), Cells(iCntr, lCol)).Font.Bold = False
For jCntr = 2 To lCol
If vMax < Cells(iCntr, jCntr) Then
vMax = Cells(iCntr, jCntr)
iMaxCol = jCntr
Cells(iCntr, iMaxCol).Font.Bold = True
Download the file below and Click on the FindMax button and Explore the Code.
Here is the scree-shot of the example which is explained above.
Download the example file and Explore it.
ANALYSISTABS -Last Column with Data in a row