简体   繁体   中英

excel vba select range of a table

I want to select a table, it will have fixed columns(4 of them) but can have any number of rows, empty rows as well. How will I select a table range?

在此处输入图片说明

For example, the current selection is B2 to E5

How can I get this programmatically in VBA?

Here is how you can set a reference to the Table. You should watch: Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset) . It will give you a better understanding of Ranges, Worksheets and the Excel object model.

Dim Target As Range
With Worksheets("SheetName")
    Set Target = .Range("B2:E2", .Range("B" & .Rows.Count).End(xlUp))
End With

Assuming your table always starts in B2 and has always a width of 4 columns you could use something like this to get the lastrow over all 4 columns:

Function getlastrow() As Integer
    Dim i As Integer
    getlastrow = 0
    With Worksheets("YourWorksheet")
        For i = 0 To 3
            'starting with 2+i=2 (column B) and End with 2+i=5 (column E)
            If (.Cells(.Rows.Count, 2 + i).End(xlUp).Row) > getlastrow Then 
                getlastrow = .Cells(.Rows.Count, 2 + i).End(xlUp).Row
            End If
        Next i
    End With
End Function

With this information you can set your range:

Sub SetRange()
    Dim myrange As Range
    With Worksheets("Tabelle1")
        Set myrange = .Range("B2:E" & getlastrow)
    End With
End Sub

try,

Worksheets("Sheet3").Range("Table1[#All]").Select
'or,
Worksheets("Sheet3").ListObjects("Table1").Range.Select

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