简体   繁体   中英

Location of first cell in an excel table

I use Excel tables a lot. It makes it possible to have multiple tables in one worksheet. But I have got into a problem in VBA which I do not know how to solve.

Let us say that I have a table called "tbl" in my spreadsheet. It contains the following data:

id value
1  1000
1  2000
2  3000
2  4000

I have the following code which works:

Sub test()
    Dim rng As Range
    Dim arr() As Variant
    Set rng = ActiveSheet.ListObjects("tbl").DataBodyRange
    arr = rng.Value
End Sub

This code will put the whole table into arr . But there are situations where I only want some rows in the table. Let us say that I want row 4 and 5 ie:

2  3000
2  4000

The following code will do the trick:

arr = Range("A4:B5")

But there are cases where I have many tables located in different places in my spreadsheet. Therefore I need to work out where the first cell in the table is located (upper left). If it is located in K1, I need to get both the column and the row (K and 1).

Is there an easy way to do this?

Use Cells():

Sub test()
Dim rng As Range
Dim arr() As Variant
Set rng = ActiveSheet.ListObjects("tbl").DataBodyRange
arr = ActiveSheet.Range(rng.Cells(3, 1), rng.Cells(4, 2)).Value    
End Sub

If you just want the third and fourth data rows (ie fourth and fifth rows if you count the heading row), you could use

Sub test()
    Dim rng As Range
    Dim arr() As Variant
    Set rng = ActiveSheet.ListObjects("tbl").DataBodyRange
    arr = rng.Rows("3:4").Value
    'or
    arr = rng.Range("A3:B4").Value
End Sub

Because the Rows and Range properties are being applied to the rng object, the references ( "3:4" and "A3:B4" ) are relative to the start of the rng object.

So you could also get the worksheet address of the first cell in rng by using rng.Range("A1").Address (or rng.Cells(1, 1).Address ), or you can get the first cell's worksheet row and column by just using rng.Row and rng.Column respectively (they both default to returning the value for the first cell).

The first cell in a table has some unique properties:

-It is not empty

-The cell above it is null

-The cell to the left of it is null

-The cell below it is not null

Using these properties you can do something like:

1) Loop over every cell

2) If that cell has the above properties, then it is a "top left" cell

3) Do whatever with that table

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