简体   繁体   中英

Formatting as a table dynamically Excel VBA

I would like to format a certain range in a worksheet as a table in Excel. The formatting will always start in row 10. In order to do so, I have written the following code:

Set rng = Range(Range("B10"), Range("B10").End(xlUp).SpecialCells(xlLastCell))
Set table = Sheets("Results").ListObjects.Add(xlSrcRange, rng, , xlYes)
table.TableStyle = "TableStyleMedium13"

As of now, the formatting is done from row 10 until the end of the worksheet - even in empty rows. However, I would like the table to be formatted only up until the last row of data and for it to do this dynamically given the fact that the amount of data will vary. How can I do this?

The code below will format all cells from "B10" until last row with data in Column B (it will also format blank rows in the middle, in case you have gaps).

Dim LastRow As Long

With Sheets("Results")
    ' find last row with data in Column B
    LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row

    ' set Rng from B10 untill last row with data in Column B
    Set Rng = Range("B10:B" & LastRow)
    Set Table = .ListObjects.Add(xlSrcRange, Rng, , xlYes)
    Table.TableStyle = "TableStyleMedium13"
End With
Range("B" & Rows.Count).End(xlUp)

这应该起作用-将仅标识最后填充的行。

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