简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM