Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear entire row data except the first row using excel VBA

I am using below code to clear contents from A2:H2 rows except the first one where I have the header. This code works well if there are no blank cells in between. But how can I clear everything eventhough there is a blank cell?

Sub Clear()

Dim s1Sheet As Worksheet

Set s1Sheet = Workbooks("StockScreen.xlsm").Sheets("TimeStampWork")

s1Sheet.Range(s1Sheet.Range("A2:H2"), s1Sheet.Range("A2:H2").End(xlDown)).ClearContents

End Sub
like image 625
acr Avatar asked Sep 01 '17 05:09

acr


People also ask

How do I delete all rows except the first header row in Excel VBA?

In the Microsoft Visual Basic for Applications window, click Insert > Module. Then copy and paste the following VBA code into the Code window. 3. Press the F5 key to run the code, then all rows except the first header row are deleted from the active worksheet immediately.

How do you delete all rows below a certain row in Excel VBA?

VBA code: Delete all rows below active cell row in ExcelPress the F5 key to run the code. Then all rows below active cell row (include the active cell row) are deleted immediately.

How do you clear the contents of a row in Excel VBA?

In VBA, there is a method called ClearContents that you can use to clear values and formulas from a cell, range of cells, and the entire worksheet. To use this method, first, you need to define the expression somewhere you want to clear the content, and then type “. ClearContents”.

How do I delete everything except headers in Excel?

Which activities can I use to delete all rows except headers? Use Excel Application Scope to open the Excel file. From there, do a Read Range on the entire sheet, with the Output to variable “mysheet”. Then use the Delete Range activity, set the Range property to “A2:Z” & mysheet.


2 Answers

Below is my sample code:

Sub ClearContentExceptFirst()
    Rows("2:" & Rows.Count).ClearContents
End Sub
like image 51
bluetata Avatar answered Sep 22 '22 07:09

bluetata


If you simply want to delete the entire row from a specific row number to a specific row number, you can avoid using the Range and Cell properties, but instead you can use the Rows property:

s1Sheett.Rows("2:10").ClearContents

Or if you want to delete the everything from a specific row number to the last row with data, you can use:

s1Sheett.Rows("2:" & currentSheet.Rows.Count).ClearContents
like image 45
Jurjen Avatar answered Sep 22 '22 07:09

Jurjen