[英]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. 我能够找到工作表中的最后一列,但是对于特定的行,我需要找到最后一列,这对于excel中的每张工作表都会有所不同,并且每次运行都会有所不同。 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 : 更新:尝试使用下面的代码,但是显示错误代码91。函数是:
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. 只需将i
替换为行号即可。
This is the function that I am using for lastColumn per specific row: 这是我用于每个特定行的lastColumn的函数:
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
. 它sheetName
可选参数sheetName
和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. 这会让你nr。 of columns from the line "5", if you want another line just change the 5 with whatever line you need. 行“ 5”中的列数,如果需要另一行,只需将5更改为所需的行即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.