2017-08-17 145 views
0

我想清除包含最後一個空白單元格的整個單元格。這就是我正在努力的工作,但它不工作。其他代碼會影響它嗎?由於用於清除最後一個單元格和最後一個單元格的公式的VBA代碼

Dim myLastRow As Long 
Dim clearCell As Long 

    Application.ScreenUpdating = False 

' Find last row 
    myLastRow = Cells(Rows.Count, "C").End(xlUp).Row 

' Loop through range 
    For clearCell = 4 To myLastRow 
     If Cells(clearCell, "C").Value = "" Then Range(Cells(clearCell, "C"), Cells(clearCell, "C")).Clear 
    Next clearCell 

    Application.ScreenUpdating = True 
+0

你想清楚了一切嗎?嘗試更改爲'Cells(clearCell,「C」)。Value <>「」'您正在製作If等於空白,並且您需要如果不同空白 – danieltakeshi

+0

空白處的單元格可以查看,但公式在那裏,我想刪除當它到達最後一個空白單元格時的公式 – Mils

+0

只有**最後一個**空白單元格?或者所有空白的單元格?或者只有最後一個單元格,如果它是空白的?你的意思是「但它不起作用」。 – YowE3K

回答

1

我看不到任何會導致錯誤在你的代碼,不是事實,你引用不與正在使用的紙張等資格 - 這意味着一切都將默認操作上ActiveSheet這可能不是您希望它工作的工作表。

假設你要處理的板材具有「斯托」的Name,下面的代碼應該是更安全:

Dim myLastRow As Long 
Dim clearCell As Long 

Application.ScreenUpdating = False 

'Use a "With" block to save typing Worksheets("Stow") in lots of places 
'(e.g. within the block we can type ".Cells" instead of "Worksheets("Stow").Cells" and 
' ".Rows" instead of "Worksheets("Stow").Rows") 
With Worksheets("Stow") 
    ' Find last row 
    myLastRow = .Cells(.Rows.Count, "C").End(xlUp).Row 

    ' Loop through range 
    For clearCell = 4 To myLastRow 
     ''Clear any cells with a value of "" 
     'If .Cells(clearCell, "C").Value = "" Then .Cells(clearCell, "C").Clear 

     'Clear any cells with a value of "-" 
     If .Cells(clearCell, "C").Value = "-" Then .Cells(clearCell, "C").Clear 
    Next clearCell 
End With 
Application.ScreenUpdating = True 
+0

多數民衆贊成非常感謝。我剛剛在玩代碼,並考慮到你說的和之前的代碼,我用它來幫助我工作表(「Stow」)。激活我有點新手,如果你還沒有猜到 – Mils

+0

@Mils 'Worksheets(「Stow」)。Activate'會讓Stow成爲活動工作表,然後你的代碼可能會像現在這樣工作。但使用'Activate'和'Select'是一個不好的習慣,因爲它會導致意想不到的事情發生(當你沒有激活你認爲正在使用的工作表/單元格),並且會降低你的代碼速度。任何有意編寫VBA代碼的人都應該閱讀[如何避免在Excel VBA中使用Select](https://stackoverflow.com/q/10714251/6535336)。 – YowE3K

相關問題