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
ws.Cells(i, ws.Columns.Count).End(xlToLeft).Column
wherei
= the number of the row. – dwirony