刪除空白單元格的VBA程式碼

刪除空白單元格的VBA程式碼

知道為什麼這行不通嗎?我不斷收到運行時錯誤 1004:應用程式定義或物件定義錯誤。如果第一個單元格為空,我試圖刪除整個行部分,然後如果它不為空,則刪除所有空行,直到有一行包含值。這只是為了輕鬆清理電子表格。我已附上程式碼。在此輸入影像描述

Private Sub checkRows()

'H or 8
If IsEmpty(Range("A827").Value) = True Then
    Rows("825:925").EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
Else
    Rows("827:925").Select
    Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete
End If

'G or 7
If IsEmpty(Range("A725").Value) = True Then
    Rows("723:823").EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
Else
    Rows("725:823").Select
    Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete
End If

'F or 6
If IsEmpty(Range("A623").Value) = True Then
    Rows("621:721").EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
Else
    Rows("623:721").Select
    Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete
End If

'E or 5
If IsEmpty(Range("A521").Value) = True Then
    Rows("519:619").EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
Else
    Rows("521:619").Select
    Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete
End If

'D or 4
If IsEmpty(Range("A419").Value) = True Then
    Rows("417:517").EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
Else
    Rows("419:517").Select
    Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete
End If

'C or 3
If IsEmpty(Range("A317").Value) = True Then
    Rows("315:415").EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
Else
    Rows("317:415").Select
    Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete
End If

'B or 2
If IsEmpty(Range("A215").Value) = True Then
    Rows("213:313").EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
Else
    Rows("215:313").Select
    Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete
End If

'A or 1
If IsEmpty(Range("A113").Value) = True Then
    Rows("111:211").EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
Else
    Rows("113:211").Select
    Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete
End If

'RP
If IsEmpty(Range("A9").Value) = True Then
    Rows("7:107").EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
Else
    Rows("9:107").Select
    Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete
End If

End Sub

VBA視窗

答案1

您不能Rows()與列引用一起使用。只需將第一部分更改為僅行即可。

If IsEmpty(Range("A827").Value) = True Then
    Rows("825:925").EntireRow.Delete XlDeleteShiftDirection.xlShiftUp
Else
    Rows("827:925").EntireRow.SpecialCells(xlBlanks).EntireRow.Delete
End If

或者你可以這樣做Range("A825:A925").EntireRow.Delete ...

答案2

未使用「目標」範圍參數,且您沒有正確使用 rows 方法。如果這是一個靜態範圍,那麼我建議使用類似的內容:

Private Sub RemoveRows()

  If IsEmpty(ActiveSheet.Range("A827").Value) = True Then ActiveSheet.Range("A827:A925").Clear

End Sub

如果您打算傳遞範圍參數,我建議傳遞範圍的字串值而不是完整的範圍物件:

Private Sub RemoveRows(ByVal TargetRange As String)

If IsEmpty(ActiveSheet.Range("A827").Value) = True Then ActiveSheet.Range(TargetRange).Clear

End Sub

然後,要使用它,只需將範圍的字串表示形式作為參數傳遞即可:

Private Sub CallRemoveRows()

RemoveRows ("A827:A895")

End Sub

相關內容