Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save danwagnerco/afef7b344a3efdf44589 to your computer and use it in GitHub Desktop.
Save danwagnerco/afef7b344a3efdf44589 to your computer and use it in GitHub Desktop.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'INPUT : Sheet, the worksheet we'll search to find the last column
' : RowNum, the row (as a number) we're interested in
'OUTPUT : Long, the last occupied column in the specified row
'SPECIAL CASE : if a bad row number is entered (anything < 1), return 0
'EXAMPLES BELOW:
'
'assume that on MySheet, cells A1:F1 are occupied,
'but B3 is the only occupied cell in row 3
'LastColNumInRow(MySheet, 3)
'>> 2
'
'assume that EmptySheet is totally empty
'LastColNumInRow(EmptySheet, 1)
'>> 1
'
'assume that you mistakely pass in -1 for the row number on MySheet
'LastColNumInRow(MySheet, -1)
'>> 0
'
Public Function LastColNumInRow(Sheet As Worksheet, RowNum As Long) As Long
If RowNum < 1 Then
LastColNumInRow = 0
Exit Function
End If
With Sheet
LastColNumInRow = Cells(RowNum, .Columns.Count).End(xlToLeft).Column
End With
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment