簡體   English   中英

在 VBA 中查找包含特定范圍內的值的最后一列

[英]Find the Last Column which contains values in a Specific Range in VBA

我有來自 A3:O43、Q3:AE43、AG3:AU43 的 3 個正常數據范圍,所有這些單元格都填充了公式。

現在我想使用 FIND 或任何其他方式根據值識別每個范圍的最后一列。 我嘗試使用下面的代碼,但無法正確獲取列號。

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

感謝你的幫助!!

參考左上角非空白范圍(范圍)

  • 空單元格也是空白單元格,但不一定相反。
  • 包含=""'的單元格是空白的,但它不是空的(因此使用xlValues參數)。

局限性

  • 沒有合並的單元格(特定於Find方法)。
  • 沒有過濾器(特定於Find方法)。
  • 沒有隱藏單元格(行、列)(特定xlValues參數)。

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

用法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM