我必须在工作表中找到一行的最后一列。我能够找到工作表中的最后一列,但是对于特定的行,我需要找到最后一列,该列对于excel中的每个工作表都会有所不同,并且每次运行时都会有所不同。要查找最后一列,我使用了以下代码,并引用了问题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
更新: 试图使用下面的代码,但它显示错误代码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
在代码中将其调用为:
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
答案 0 :(得分:2)
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
只需将i
替换为行号。
答案 1 :(得分:1)
这是我用于每个特定行的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
它采用可选参数sheetName
和rowToCheck
。这是为您的案例运行它的方法:
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
答案 2 :(得分:0)
试试这个:
With Worksheets(set_sheet_name)
LastCol = .Cells(5, .Columns.Count).End(xlToLeft).Column
End With
这会让你nr。来自第" 5"行的列,如果你想要另一行,只需用你需要的任何一行改变5。