麻烦运行简单的空白行删除

时间:2015-06-27 07:55:22

标签: excel vba excel-vba excel-2013

我是Macros的新手,但我怀疑其他问题可能会在这里引起争议。

以下是删除多表工作簿中空白行的简单宏。是的,此处的工作表是第9页。

Sub FnDelete­BlankRows()
Dim mwb As Work­Book
Set mwb = Active­Work­Book
For x = mwb.Sheets(“Sheet1”).Cells.SpecialCells(xlCellTypeLastCell).Row 1 Step –1
If WorksheetFunction.CountA(mwb.Sheets(“Sheet1”).Rows(x)) = 0 Then
mwb.Sheets(“Sheet9”).Rows(x).Delete
End If
Next
End Sub

出现的错误是“用户定义的类型未定义”

之前我曾尝试过以下代码并收到“语法错误”。我尝试了谷歌搜索,并做了所有标准的修复(确保宏已启用,设计师关闭等,我甚至将我的工作表保存为xltm)

Sub RemoveRows()
Dim lastrow As Long
Dim ISEmpty As Long
Count how many records in the list. This is done so that the Do loop has a finish point.

lastrow = Application.CountA(Range(“A:A”))
‘Start at the top of the list
Range(“A1″).Select

Loop until the end of the list
Do While ActiveCell.Row < lastrow
Assign number of non empty cells in the row
ISEmpty = Application.CountA(ActiveCell.EntireRow)
If ISEmpty = 0 then delete the row, if not move down a cell into the next row
If ISEmpty = 0 Then
ActiveCell.EntireRow.Delete 
Else
ActiveCell.Offset(1, 0).Select
End If
LoopEnd Sub

尽管我很乐意学习VBA的优点,但我真的很想学习如何使用最少的自定义来开发宏工作。

由于

1 个答案:

答案 0 :(得分:1)

试试这个 - 确保将Sheet1更改为您正在处理的工作表。

经过测试 Excel 2010

Option Explicit
'// Delete blank Rows
Sub xlDeleteBlankRows()
   Dim xlWb As Workbook
   Dim i As Long
   Set xlWb = ActiveWorkbook
   For i = xlWb.Sheets("Sheet1").Cells.SpecialCells(xlCellTypeLastCell).row To 1 Step -1
      If WorksheetFunction.CountA(xlWb.Sheets("Sheet1").Rows(i)) = 0 Then
         xlWb.Sheets("Sheet1").Rows(i).Delete
      End If
   Next
End Sub
Option Explicit
Sub xlRemoveRows()
    Dim lastrow As Long
    Dim ISEmpty As Long

    '// Count how many records in the list. This is done so that the Do loop has a finish point.
    lastrow = Application.CountA(Range("A:A"))

    '// Start at the top of the list
    Range("A1").Select

    '// Loop until the end of the list
    Do While ActiveCell.Row < lastrow

    '// Assign number of non empty cells in the row
    ISEmpty = Application.CountA(ActiveCell.EntireRow)
            '// If ISEmpty = 0 then delete the row, if not move down a cell into the next row
            If ISEmpty = 0 Then
            ActiveCell.EntireRow.Delete
            Else
        ActiveCell.Offset(1, 0).Select
        End If
    Loop
End Sub

请参阅MSDN上的有用文章Getting Started with VBA in Excel 2010&amp; 2013

Option Explicit
Sub xlDeleteRow()
    Dim lngRow, lngCrnt, lngCol As Long
    Dim xlBln As Boolean
    Application.ScreenUpdating = False
    lngRow = Cells(Rows.count, "A").End(xlUp).Row
    For lngCrnt = lngRow To 1 Step -1
        xlBln = False
        For lngCol = 1 To 2
            If Cells(lngCrnt, lngCol).Value <> vbNullString Then
                xlBln = True
                Exit For
            End If
        Next lngCol
        If Not xlBln Then Rows(lngCrnt).Delete
    Next lngCrnt
    Application.ScreenUpdating = True
End Sub