检查每行使用的lastcolumn

每行可以有不同的最后一次使用的列。我想要检查每列是最后一列的列。 我怎么能做到这一点?

Option Explicit Sub Sample() Dim ws As Worksheet Dim LastCol As Long Dim rng As Range Set ws = Sheets("Sheet1") Set rng = ws.Cells.Find(What:="*", _ After:=ws.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious, _ MatchCase:=False) If rng Is Nothing Then LastCol = 1 Else LastCol = rng.Column End If Debug.Print LastCol End Sub 

此代码用于查找最后一列(对于所有行都是通用的)。 但是我想检查每行不同的最后使用的列。

有很多不同的方法,下面是一个使用以下数据的演示。 它还为您提供了一种使用列A查找最后一行的方法。您可能需要编写一些将列号转换为列字母的方法。

还要注意,你可以指定被testing的行/列,使用Cells(rw, Columns.Count)一个variables,例如Cells(rw, Columns.Count)Cells(Rows.Count, "A")一个常量,例如"A"

最后,特别是如果您使用多个工作表,您可能还需要注意指定您正在使用的数据所在的工作表,如Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row 。 在我的示例中,除非以这种方式“限定”,否则将使用ActiveSheet上的数据。 所以在运行这个代码示例之前,请确保select包含您的数据的工作表。

在这里输入图像描述

 Option Explicit Sub lastCol() Dim lCol As Long, rw As Long For rw = 1 To Cells(Rows.Count, "A").End(xlUp).Row lCol = Cells(rw, Columns.Count).End(xlToLeft).Column MsgBox "For row " & rw & ", last column is " & lCol Next rw End Sub 

编辑

 Sub lrow() Dim lCol As Long, rw As Long For rw = 1 To Cells(Rows.Count, "A").End(xlUp).Row lCol = Cells(rw, Columns.Count).End(xlToLeft).Column If Cells(rw, lCol).Value = "rajani" Then MsgBox "Row " & rw & ", last column " & lCol & " contains rajani" End If Next rw End Sub