Use Last Column for a Range(F:LastColumn)

前端 未结 3 766
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-21 01:19

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

相关标签:
3条回答
  • 2021-01-21 01:45

    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
    
    0 讨论(0)
  • 2021-01-21 01:46
        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
    
    0 讨论(0)
  • 2021-01-21 01:53

    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
    
    0 讨论(0)
提交回复
热议问题