user9351236
user9351236

Reputation: 143

Last column of a specific row in Excel

I have to find the last column of a row in a sheet. I am able to find the last column in the sheet, but for a particular row, I need to find the last column which will vary for every sheet in the excel, and it will vary at every run. To find the last column, I have used the below code, with reference from the question Finding last column across multiple sheets in a function:

For Each ws In ThisWorkbook.Sheets
 lc = ws.Cells.Find("*", SearchOrder:=xlByColumns,      
 SearchDirection:=xlPrevious).Column
 Debug.Print ws.Name, lc
 MsgBox lc
 Next ws

Updated: Trying to use the below code, but its showing error code 91. Function is :

 Function lastColumn(Optional sheetName As String, Optional 
rowToCheck  As Long =  1) As Long

Dim ws  As Worksheet

If sheetName = vbNullString Then
    Set ws = ActiveSheet
Else
    Set ws = Worksheets(sheetName)
End If

lastColumn = ws.Cells(rowToCheck, ws.Columns.Count).End(xlToLeft).Column

End Function

Calling it in the code as:

For Each ws In ThisWorkbook.Worksheets

    i = ws.Columns(2).Find("Total").Row (error code as 91)
    Debug.Print lastColumn(ws.Name, i)
Next ws

Upvotes: 0

Views: 10147

Answers (3)

Vityata
Vityata

Reputation: 43595

This is the function that I am using for lastColumn per specific row:

Function lastColumn(Optional sheetName As String, Optional rowToCheck As Long = 1) As Long

    Dim ws  As Worksheet

    If sheetName = vbNullString Then
        Set ws = ActiveSheet
    Else
        Set ws = Worksheets(sheetName)
    End If

    lastColumn = ws.Cells(rowToCheck, ws.Columns.Count).End(xlToLeft).Column

End Function

It takes optional arguments sheetName and rowToCheck. This is a way to run it for your case:

Public Sub TestMe()

    Dim ws      As Worksheet
    Dim lc      As Long
    lc  = 8

    For Each ws In ThisWorkbook.Worksheets
        Debug.Print lastColumn(ws.Name, lc)
    Next ws

End Sub

Upvotes: 1

Ionut
Ionut

Reputation: 91

Try this :

With Worksheets(set_sheet_name)
    LastCol = .Cells(5, .Columns.Count).End(xlToLeft).Column
End With

this will get you nr. of columns from the line "5", if you want another line just change the 5 with whatever line you need.

Upvotes: 0

dwirony
dwirony

Reputation: 5450

Sub Test()

For Each ws In ThisWorkbook.Sheets
    lc = ws.Cells(i, ws.Columns.Count).End(xlToLeft).Column
    Debug.Print ws.Name, lc
    MsgBox lc
Next ws

End Sub

Just replace i with the row number.

Upvotes: 2

Related Questions