Find last column assigned in Range

一世执手 提交于 2019-12-13 21:18:23

问题


I need to find out the column that is the last column in a range that is defined with:

Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange

回答1:


First things first

Never use UsedRange to set your range. I have explained it HERE as to why you shouldn't use UsedRange

Set RngSource = ActiveWorkbook.ActiveSheet.UsedRange

Find the Last Column that has data and the Last Row which has data and then set your range. So your question of finding the last column from the range will not arise. Here is an example

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



回答2:


Use End(xlToRight) with an activecell.



来源:https://stackoverflow.com/questions/16309197/find-last-column-assigned-in-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!