2017-06-09 92 views
0

我試圖編寫一個宏以刪除命名範圍中的空白單元格(值「」,非空,因爲可能包含公式),並且在修正運行時錯誤時遇到問題'424',即「需要對象」。在命名範圍內循環以刪除包含的空白單元格

Sub DeleteBlankCellsInANamedRange() 
'Deletes empty cells in a named range (shifts cells up) 

For Each c In Range("myNamedRange") 
    If c.Value = 0 Then 
     myNamedRange.Cells.Delete Shift:=xlUp 'error 424 throws here 
    End If 
Next c 
MsgBox "Macro completed" 

End Sub 

我認爲問題是與語法,並一直在嘗試不同的東西沒有運氣。有任何想法嗎?請分享。謝謝你的幫助!

+0

使用'Option Explicit'。使用'Range(「myNamedRange」)。Cells'它可以是''myNamedRange''或'myNamedRange'。使用'c.Delete ...' – cyboashu

+0

謝謝@cyboashu ---像魅力一樣工作。 – PBG

+0

其實@cyboashu,宏刪除範圍內的每個單元格。整個範圍不是空白。對此有何想法? – PBG

回答

0
Sub DeleteBlankCellsInANamedRange() 
'Deletes empty cells in a named range (shifts cells up) 

Dim rngCell  As Range 
Dim rngDelete As Range 

For Each rngCell In Range("myNamedRange").Cells 
    If rngCell.Value = 0 Then 

     If Not rngDelete Is Nothing Then 
      Set rngDelete = Union(rngDelete, rngCell) 
     Else 
      Set rngDelete = rngCell 
     End If 


    End If 
Next 

    If Not rngDelete Is Nothing Then 
     rngDelete.Delete Shift:=xlUp 
    End If 

MsgBox "Macro completed" 

End Sub 
+0

嗨@cyboashu ---非常感謝,但它不起作用。 – PBG

+0

我想要刪除的'空白'單元格包含公式,特別是條件公式,它們將值設置爲空白(「」)給定特定條件。 – PBG

+0

如果你想刪除'「」'然後使用'如果rngCell.Value =「」然後' – cyboashu

相關問題