0
votes

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
3
Use ws.Cells(i, ws.Columns.Count).End(xlToLeft).Column where i = the number of the row.dwirony
Error 91 means it didn't find the word "Total" in column B of the sheet you checked. Are certain every single sheet has a cell with "Total" in it somewhere in column B? You may need to add a check to make sure it's being found properly.tigeravatar

3 Answers

2
votes
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.

1
votes

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
0
votes

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.