Home » excel » excel – Column count for particular sheet

excel – Column count for particular sheet

Posted by: admin May 14, 2020 Leave a comment

Function getMaxColumnCount() As Long

         Dim lColumn As Long, sh As Worksheet
         Set sh = ThisWorkbook.Sheets("Sheet1")
        lColumn = sh.Cells(6, Columns.count).End(xlToLeft).Column
        getMaxColumnCount = lColumn

End Function

in my sheet1 , my data started by row number 6 and column number 2 and ends up with column number 25.
Using above function , it returns maximum column count as 25

Now i one scenrio like there are two sets of data

In Same Sheet only two sets of data
frist set of data (6,2) to (6,25)
second set of data starts from (6,30) to (6,50) for that i want output as 20 for that using above code what change should i do

How to&Answers:

So just to be clear, if your first set of data has 23 columns and 2nd set has 20 columns and lets say there is a 3rd set which has 5 columns then you want 5 as an answer? Also will all set have at least one blank cell in betwen? – Siddharth Rout 5 mins ago Edit

@Siddharth Rout yes it is like that only – uservba12 2 mins ago

Is this what you are trying?

Logic: Get the last column and then find the blank cell before that. Subtract to get column count.


Option Explicit

Function GetLastSetColumnCount() As Long
    Dim lCol As Long
    Dim BlankCol As Long
    Dim i As Long
    Dim ws As Worksheet

    Set ws = Activesheet '~~> OR relevant sheet

    With ws
        lCol = .Cells(6, .Columns.Count).End(xlToLeft).Column

        For i = lCol To 1 Step -1
            If Len(Trim(.Cells(6, i).Value)) = 0 Then
                BlankCol = i
                Exit For
            End If
        Next i
    End With

    GetLastSetColumnCount = lCol - BlankCol
End Function