Use Last Column for a Range(F:LastColumn)

2020-04-10 09:03发布

I am trying to use Last column for my range: WS.range("F2:LastCol" & LastRow).Cells my sub works for

WS.range("F2:K" & LastRow).Cells but the Last Column is dynamic and keeps changing

Thanks

Sub QQ()

Dim LastRow As Long
Dim LastCol As Long
Dim WS As Worksheet
Dim rCell As range

Set WS = Sheets("sheet1")

LastRow = WS.range("F" & WS.Rows.Count).End(xlUp).Row

LastCol = Cells(2, .Columns.Count).End(xlToLeft).Column
'Also tried: LastCol=rgRange.Cells(rgRange.Count).Column 

For Each rCell In WS.range("F2:LastCol" & LastRow).Cells

STUFF 'The stuff works for WS.range("F2:K" & LastRow).Cells

End Sub

3条回答
不美不萌又怎样
2楼-- · 2020-04-10 09:43

LastCol is a number, and the syntax you're using to specify the range requires a letter.

You can find out the column letter for the column number and pass it in to your range definition like this:

Sub DynamicRange()
    Dim startCol As String
    Dim startRow As Long
    Dim lastRow As Long
    Dim lastCol As Long
    Dim myCol As String
    Dim ws As Worksheet
    Dim rng As Range
    Dim cell as Range

    Set ws = ThisWorkbook.Sheets("Sheet1")
    startCol = "F"
    startRow = 2
    lastRow = ws.Range(startCol & ws.Rows.Count).End(xlUp).Row
    lastCol = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column
    myCol = GetColumnLetter(lastCol)

    Set rng = ws.Range(startCol & startRow & ":" & myCol & lastRow)

    For Each cell In rng
       ' do stuff
    Next cell

    ' check the range we've set
    Debug.Print rng.Address

End Sub

Function GetColumnLetter(colNum As Long) As String
    Dim vArr
    vArr = Split(Cells(1, colNum).Address(True, False), "$")
    GetColumnLetter = vArr(0)
End Function
查看更多
Lonely孤独者°
3楼-- · 2020-04-10 09:45

Please try to define your loop this way:

For Each rCell In WS.range(ws.Range("F2"), Ws.Cells(LastRow, LastCol)).Cells

or it could go shorter way with this solution (if WS is Activesheet):

For Each rCell In WS.range("F2", Cells(LastRow, LastCol)).Cells
查看更多
够拽才男人
4楼-- · 2020-04-10 09:58
    dim wb As Workbook
    dim ws As Worksheet
    Set wb = ThisWorkbook
    Set ws = wb.Sheets("sheet name")    
    Set ListObj = ws.ListObjects("table name")

If ListObj Is Nothing Then
        Set ListObj = ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$15:$Q$16"), , xlYes)
        ListObj.Name = "new table"
Else
        lastRow = ListObj.Range.Columns(1).cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

        ListObj.Resize Range("$B$15:W" & lastRow + 2)
End if
查看更多
登录 后发表回答