• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Deleting data from excel sheet

Ipek

New Member
I have a macro that runs and populate sheet2 with data from database. I want to clear contents of sheet2 before loading data to it. I want to clear contents of sheet2 from A2 cell up to the last row in the sheet. how do I code this in VBA 2007, thanks
 
Hi Ipek,

Try below code:

Code:
Sub ClearContent()
 
Dim ws As Worksheet
Dim lastrow As Long
 
Set ws = ThisWorkbook.Worksheets("Sheet2")
 
Application.ScreenUpdating = False
With ws
 
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
For i = 2 To lastrow
  ws.Range("A" & i).ClearContents
Next i
Application.ScreenUpdating = True
End Sub

Regards,
 
Hi, Ipek!

I suggest you to replace this part of Somendra Misra's code:
Code:
For i = 2 To lastrow
  ws.Range("A" & i).ClearContents
Next i
with this:
Code:
  ws.Range("A2:A" & lastrow).ClearContents

It'll run once and avoid the loop for each row. In large ranges it's highly noticeable.

But that only clears column A, so if you want to clear all the columns use this:
Code:
  With ws
    If .Rows.Count > 1 Then Range(.Rows(2), .Rows(.Rows.Count)).ClearContents
  End With

Regards!
 
Back
Top