Use Last Column for a Range(F:LastColumn)

前端 未结 3 786
爱一瞬间的悲伤
爱一瞬间的悲伤 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
    

提交回复
热议问题