Home » excel » excel – Find last column with data, clear two columns from right

excel – Find last column with data, clear two columns from right

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have VBA for copy paste function. I would like to have the same for clear cells function. I want to find last cell in rows 10:31 with data from the right and clear two last columns in rows 10:31.

I use lastcolumn = Cells(1, Columns.Count).End(xlToRight).Column to find last cell with data from the right.

How I can set rows 10:31 and implement ClearContents to do the work?

10 data data1 data2 data3 data4 data5 data6 data7 data8
11 data data1 data2 data3 data4 data5 data6 data7 data8
12 data data1 data2 data3 data4 data5 data6 data7 data8
13 data data1 data2 data3 data4 data5 data6 data7 data8
14 data data1 data2 data3 data4 data5 data6 data7 data8
...
31 data data1 data2 data3 data4 data5 data6 data7 data8

The idea is that if I click button once “data8 and data7” will be cleared, then I click button once again “data6 and data5” will be cleared. Again button clicked “data4 and data3” are gone and so on…
Here is my code:

Sub Remove()
Application.ScreenUpdating = False
Dim lastcolumn As Integer
Dim lastrow As Long

'finds the last used column coming from the right
lastcolumn = Cells(1, Columns.Count).End(xlToRight).Column
Worksheets("Price calculation").Range("10:31").Offset(0, 1).ClearContents

Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
How to&Answers:

If you just want a specific range of cells contents cleared, name the exact range such as:

With Worksheets("Price calculation")
    lc = .cells(10,.columns.count).end(xltoleft).column
    .Range(.cells(10,lc-2),.cells(31,lc)).ClearContents
End with