查找在Range中分配的最后一列

时间:2013-04-30 21:24:18

标签: excel vba range

我需要找出用以下定义的范围中最后一列的列:

Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange

2 个答案:

答案 0 :(得分:1)

首先要做的事情

切勿使用UsedRange来设置范围。我已经解释了HERE为什么你不应该使用UsedRange

Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange

找到包含数据的最后一列和包含数据的最后一行,然后设置范围。因此,您不会出现从范围中找到最后一列的问题。这是一个例子

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range
    Dim lRow As Long, lCol As Long

    '~~> Set your worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            '~~> Find Last Row
            lRow = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row

            '~~> Find Last Column
            lCol = .Cells.Find(What:="*", _
                   After:=.Range("A1"), _
                   Lookat:=xlPart, _
                   LookIn:=xlFormulas, _
                   SearchOrder:=xlByColumns, _
                   SearchDirection:=xlPrevious, _
                   MatchCase:=False).Column
        Else
            lRow = 1: lCol = 1
        End If

        '~~> Set your range
        Set rng = .Range(.Cells(1, 1), .Cells(lRow, lCol))

        Debug.Print rng.Address
    End With
End Sub

答案 1 :(得分:0)

将End(xlToRight)与activecell一起使用。