简体   繁体   English

使用VBA在Excel中删除空行

[英]Delete Empty Rows In Excel Using VBA

I am trying to delete empty rows in excel by using below code: 我正在尝试通过使用以下代码来删除excel中的空行:

iRowLast = .Cells(.Rows.Count, iCol_Exp).End(xlUp).Row
Set r = .Range("A1:F48")
Set Z = ActiveSheet.Range("A1:Z50")

For i = iRowLast To 10 Step (-1)
    r.Rows(i).Replace What:=Chr(32), Replacement:="", LookAt:=xlPart
    If WorksheetFunction.CountA(r.Rows(i)) = 0 Then Z.Rows(i).Delete
Next

I am looking for empty cell and spaces as well and want to delete the row only if all the respective columns are empty or have spaces with out any actual data. 我也在寻找空单元格和空格,并且仅在所有相应列均为空或没有任何实际数据的空格时才删除该行。

The problem in this code is it is also deleting spaces between data in excel sheet. 此代码中的问题是它也在Excel工作表中删除数据之间的空格。 Please provide suggestion how can I avoid that. 请提供建议,我该如何避免这种情况。

If you don't mind that the cells which have both data and leading/lagging spaces are modified (trimmed), then Siddharth's response is really neat. 如果您不介意同时修改(修剪)了同时具有数据和前导/滞后空格的像元,则Siddharth的响应确实很整洁。 Another option is to check whether the cell is composed entirely of spaces ... something like ... 另一种选择是检查单元格是否完全由空格组成...类似...

iRowLast = .Cells(.Rows.Count, iCol_Exp).End(xlUp).Row
Set r = .Range("A1:F48")
Set Z = ActiveSheet.Range("A1:Z50")

For i = iRowLast To 10 Step (-1)
    'r.Rows(i).Replace What:=Chr(32), Replacement:="", LookAt:=xlPart
    For Each vcell In r.Rows(i).Columns
        If Len(Replace(vcell, " ", "")) = 0 Then vcell = ""
    Next

    If WorksheetFunction.CountA(r.Rows(i)) = 0 Then Z.Rows(i).Delete
Next

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

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