简体   繁体   English

动态格式化为表格Excel VBA

[英]Formatting as a table dynamically Excel VBA

I would like to format a certain range in a worksheet as a table in Excel. 我想将工作表中的某个范围格式化为Excel中的表格。 The formatting will always start in row 10. In order to do so, I have written the following code: 格式总是从第10行开始。为此,我编写了以下代码:

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. 到目前为止,格式化是从第10行到工作表的末尾-甚至是空行。 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). 下面的代码将从B10到最后一行的所有单元格格式化,并在B列中提供数据(如果有空格,它还将在中间格式化空白行)。

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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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