简体   繁体   English

Excel VBA删除表中的空行

[英]Excel VBA Delete empty rows in table

I have a table tabelaClientes in Sheet " Clientes " and I want to delete the rows where the field " Nome " is empty. 我在工作表“ Clientes ”中有一个表tabelaClientes ,我想删除字段“ Nome ”为空的行。

How do I do that? 我怎么做?

This is what I'm trying: 这是我正在尝试的:

Sub Cliente()
Dim ws As Worksheet
Dim row As Range

Set ws = Sheets("Clientes")

For Each row In ws.[tabelaClientes[Nome]].Rows
     If row.Value = "" Then
        row.Delete
    End If
Next

Exit Sub

But this is deleting only some of the rows where Nome is empty, not all, why? 但这只是删除Nome为空的某些行,而不是全部,为什么?

You can use a very simple call to SpecialCells() to do that instead of using a loop. 您可以使用对SpecialCells()的非常简单的调用来执行此操作,而不是使用循环。

Range("tabelaClientes[Nome]").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

Edit: To expand on my answer because I was in a hurry. 编辑:扩大我的答案,因为我很着急。 SpecialCells mimic the menu that you will find in Excel after having pressed F5 and selected "Special cells... Blanks". SpecialCells模仿在按F5并选择“ Special cells ... Blanks”后将在Excel中找到的菜单。 This has the advantage of selecting all blanks at the same time and then delete the rows. 这样的优点是可以同时选择所有空白,然后删除行。 Iteration can be very slow if your table is getting large thus this way will save a lot of time. 如果表越来越大,迭代可能会非常慢,因此这种方式将节省大量时间。

It does seem that you cannot delete multiple non-contiguous rows in a table . 它似乎你不能删除多个不连续的行。 You can do either one of two things: 您可以执行以下两项操作之一:

1- Convert back the table to a range and change the reference to a standard excel reference 1-将表转换回范围并将参考更改为标准Excel参考

2- Loop through the results of SpecialCells(). 2-遍历SpecialCells()的结果。

Option #2 will yield in slower code because of the loop but it will still be better than looping through all cells and check if they are blank but I can understand that you may need to keep it as a table. 由于循环,选项#2的代码生成速度会变慢,但它仍然比循环遍历所有单元格并检查它们是否为空白要好,但我可以理解,您可能需要将其保留为表格。

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

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