我在Excel中记录一个宏,但是代码会抛出错误?

时间:2017-03-03 13:15:30

标签: excel vba excel-vba

我正在使用此代码

Sub Cleanse()
    '
    ' Cleanse Macro
    '
    Selection.SpecialCells(xlCellTypeBlanks).Select
    Selection.EntireRow.Delete
End Sub

我让Excel通过以下方式自动生成:

  • 按录制宏
  • 进入特殊的
  • 选择所有空白单元格
  • 在单元格上使用删除选择
  • 停止录制宏

然而,当我撤消并运行宏试图让它做同样的事情时,它说: enter image description here

2 个答案:

答案 0 :(得分:0)

您的错误是因为您的选择(在运行sub之前手动创建的选项)包括相同的单元格两次,至少一次。编辑:这可能是由于同一行上的多个单元格为空,然后您正在选择每个单元格的整行!请参阅下面的代码编辑以获得修复。

尽管Macro Recorder使用了很多,但您应尽量避免使用Select。见这里:How to avoid using Select in Excel VBA macros

因此,您的sub的更好格式是:

Sub Cleanse()        
    ' Cleanse Macro for deleting rows where cells in a range are blank
    '
    Dim myRange as Range
    ' Set the selection range to the first column in the used range.
    ' You can use this line to select any range you like.
    ' For instance if set on manual selection, you could use
    ' Set myRange = Selection. But this won't solve your actual problem.
    Set myRange = ActiveSheet.UsedRange.Columns(1)
    ' Delete all rows where a cell in myRange was blank
    myRange.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub

修改:可以在下面的所有列上循环,避免重叠EntireRow范围。

Sub Cleanse()        
    ' Cleanse Macro for deleting rows where cells in a range are blank
    '
    Dim myRange as Range
    Dim colNum as Long
    ' Cycle over all used columns
    With ActiveSheet
        For colNum = 1 To .UsedRange.Columns.Count + .UsedRange.Columns(1).Column
        ' Set the selection range to the column in used range.        
            Set myRange = .UsedRange.Columns(colNum)
            ' Delete all rows where a cell in myRange was blank
            myRange.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
        Next colNum
    End With
End Sub

答案 1 :(得分:0)

你可以使用这个子

Sub CleanSheet(sht As Worksheet)
    On Error Resume Next
    Intersect(sht.UsedRange, sht.UsedRange.SpecialCells(xlCellTypeBlanks).EntireRow).EntireRow.Delete
End Sub

由您的"主要&#34>呼叫子如下

Sub Main()
    CleanSheet Worksheets("mySheetToBeCleanedName") '<--| change "mySheetToBeCleanedName" to actual sheet name you want to clear
End Sub