简体   繁体   中英

VBA code for clearing last cell and formulas from last cell

I want to clear the whole cell including formulas from the last blank cell. Here is what i'm trying to work with but its not working. Would other code affect it? Thanks

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

I don't see anything that would cause an error in your code, other than the fact that your references aren't qualified with the sheet that is being used - which means everything will default to operating on ActiveSheet which may not be the sheet you are wanting it to work on.

Assuming the sheet you want to process has a Name of "Stow", the following code should be safer:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM