简体   繁体   中英

Excel-VBA: create named Range in row until end of cell content

Imagine an Excel sheet with some rows and some content in each row (ie different column-length for each row).

In Excel-VBA: How can I create a range-X within column-X that goes from row-cell-2 to the end of the content of this X-column ??

ie I would like to create a named range per column and each range shall start from row-2 until the end of each column-length!

Thanks for any help on this !

Sure you can use this snippet to find the last filled cell in a column and use that row number to set your range.name - just replace the "A" with whatever column you'd like.

Sub test()
Dim lastrow As Integer
 lastrow = Cells(Rows.Count, "A").End(xlUp).Row
 Range("A2:A" & lastrow).Name = "RangeColA"
End Sub

If you wanted to do it for each column you could try something like this -

Sub test()
Dim lastrow As Integer
Dim letter As String
Dim lastcol As Integer
lastcol = Cells(1, Columns.Count).End(xlToLeft).Column


For i = 65 To 65 + lastcol
 letter = Chr(i)
 lastrow = Cells(Rows.Count, letter).End(xlUp).Row
 Range(Cells(2, letter), Cells(lastrow, letter)).Name = "RangeCol" & letter
Next

End Sub

Here is another answer (inspired by Raystafarian's answer) that handles the case where the last used cell in the column appears at or above the second row and also gives more flexibility in the name:

Sub NameColumn(Col As String, Optional ColName As Variant)
    Dim n As Long
    Dim myName As String
    If IsMissing(ColName) Then ColName = "Range_" & Col
    n = Cells(Rows.Count, Col).End(xlUp).Row
    If n <= 2 Then
        Range(Col & "2").Name = ColName
    Else
        Range(Col & "2:" & Col & n).Name = ColName
    End If
End Sub

try various things in columns A through E (including leaving a blank column) then test it like this:

Sub test()
    NameColumn "A"
    NameColumn "B"
    NameColumn "C"
    NameColumn "D", "Bob"
    NameColumn "E"
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM