I have 3 Normal Data Ranges from A3:O43, Q3:AE43, AG3:AU43, and all these cells are filled with formulas.
Now I would like to identify the last column of each range based on Values using FIND or any other way. I have tried using the below code, but I'm not able to get the column numbers properly.
With UBMonthlyYTDSht
Set Rowss = .Columns("B:B").Find("*", After:=.Range("B1"), searchdirection:=xlPrevious, LookIn:=xlValues)
If Not Rowss Is Nothing Then Lrows = Rowss.Row
End With
Lcols = UBMonthlyYTDSht.Cells(1, Columns.Count).End(xlToLeft).Column
With UBMonthlyYTDSht
Set Colss = .Rows(Lrows).Find("*", After:=.Cells(Lrows, Lcols), searchdirection:=xlPrevious, LookIn:=xlValues)
If Not Colss Is Nothing Then Lcols = Colss.Column
End With
Appreciate your help!!
=""
or '
is blank, but it's not empty (hence the use of the xlValues
parameter).Limitation
Find
method specific).Find
method specific).xlValues
parameter specific).The Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Creates a reference to the range from the first cell
' of a range to its last cell with a non-blank row or column.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefTopLeftNonBlank( _
ByVal rg As Range) _
As Range
If rg Is Nothing Then Exit Function
Dim Last As Long: Last = rg.Row + rg.Rows.Count - 1 ' worksheet row
Dim lCell As Range
Set lCell = rg.Find("*", , xlValues, , xlByRows, xlPrevious)
If lCell Is Nothing Then Exit Function
With rg.Resize(rg.Rows.Count - Last + lCell.Row)
Last = .Column + .Columns.Count - 1 ' worksheet column
Set lCell = .Find("*", , xlValues, , xlByColumns, xlPrevious)
Set RefTopLeftNonBlank _
= .Resize(, .Columns.Count - Last + lCell.Column)
End With
End Function
Usage
Sub RefTopLeftNonBlankTEST()
Dim ws As Worksheet: Set ws = ActiveSheet ' be more specific
Dim rg As Range: Set rg = ws.Range("A3:O43")
Dim tlrg As Range: Set tlrg = RefTopLeftNonBlank(rg)
If Not tlrg Is Nothing Then
Debug.Print rg.Address(0, 0), tlrg.Address(0, 0)
rg.Interior.Color = xlNone
tlrg.Interior.Color = vbYellow
End If
End Sub
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.