删除空行然后在列值之前添加一行

时间:2013-12-11 21:26:05

标签: excel vba excel-vba

我是新来的,已经绞尽脑汁待了大约一个星期,试图弄明白这一点。我也到处搜索,我试图修复我的问题的每个例子都不起作用。所以,如果这是在这里的某个地方却无法找到,我道歉。

我的删除,我有一个计算机生成的电子表格,可以在Excel中创建超过2000行。一半是空的空行。我的目标是删除所有空行,然后插入行,如果列“n”的值为Y或N.

我删除了空白行,但我正在努力根据值添加行。任何帮助将不胜感激。


Sub DeleteBlankRows()
  Dim Rng As Range
  Dim WorkRng As Range

  On Error Resume Next
  xTitleId = "KutoolsforExcel"

  Set WorkRng = Application.Selection
  Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)

  xRows = WorkRng.Rows.Count
  Application.ScreenUpdating = False

  For i = xRows To 1 Step -1
    If Application.WorksheetFunction.CountA(WorkRng.Rows(i)) = 0 Then
      WorkRng.Rows(i).EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
    End If
  Next

  Application.ScreenUpdating = True
End Sub

Sub InsertRow()
  If ActiveCell = "y" Then
    Selection.EntireRow.Insert
    If ActiveCell = "n" Then
      Selection.EntireRow.Insert
    End If
  End If
End Sub

1 个答案:

答案 0 :(得分:0)

将第一个例程的逻辑与第二个例程(未测试的代码)

结合起来
Sub DeleteBlankRows()

  Const COLUMN_TO_CHECK_FOR_Y_N = 10&

  Dim Rng As Range
  Dim WorkRng As Range

  On Error Resume Next
  xTitleId = "KutoolsforExcel"

  Set WorkRng = Application.Selection
  Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)

  xRows = WorkRng.Rows.Count
  Application.ScreenUpdating = False

  ' Delete Rows
  For i = xRows To 1 Step -1
    If Application.WorksheetFunction.CountA(WorkRng.Rows(i)) = 0 Then
      WorkRng.Rows(i).EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
    End If
  Next

  ' Add Rows
  For i = xRows To 1 Step -1
    If WorkRng.Cells(i, COLUMN_TO_CHECK_FOR_Y_N) = "N" Then
      WorkRng.Rows(i).Insert
    End If
  Next

  Application.ScreenUpdating = True
End Sub

请注意,您应远离Selection和ActiveCell。请参阅this answer