Create excel ranges using column numbers in vba?

前端 未结 9 2128
误落风尘
误落风尘 2021-02-02 05:56

How is it possible to create a range in vba using the column number, rather than letter?

9条回答
  •  北恋
    北恋 (楼主)
    2021-02-02 06:19

    Range.EntireColumn

    Yes! You can use Range.EntireColumn MSDN

    dim column : column = 4
    
    dim column_range : set column_range = Sheets(1).Cells(column).EntireColumn
    

    Range("ColumnName:ColumnName")

    If you were after a specific column, you could create a hard coded column range with the syntax e.g. Range("D:D").

    However, I'd use entire column as it provides more flexibility to change that column at a later time.

    Worksheet.Columns

    Worksheet.Columns provides Range access to a column within a worksheet. MSDN

    If you would like access to the first column of the first sheet. You would call the Columns function on the worksheet.

    dim column_range: set column_range = Sheets(1).Columns(1)
    

    The Columns property is also available on any Range MSDN

    EntireRow can also be useful if you have a range for a single cell but would like to reach other cells on the row, akin to a LOOKUP

    dim id : id = 12345
    
    
    dim found : set found = Range("A:A").Find(id)
    
    if not found is Nothing then
        'Get the fourth cell from the match
        MsgBox found.EntireRow.Cells(4)
    end if
    

提交回复
热议问题