Dynamic range in vba

niicommey

New member
Joined
Dec 18, 2020
Messages
1
Reaction score
0
Points
0
Excel Version(s)
office 365 ver 18
Hello forum,
I am new to VBA and I want to use a command button to clear some ranges. How can I improve the code below such that the range will be dynamic enough to adjust when I delete or insert some new rows.

Code:
Private Sub CommandButton1_Click()
Sheets("Sheet1").Range("B19:B68") = ""
Sheets("Sheet1").Range("C19:C68") = ""
End Sub
 
Last edited by a moderator:
Perhaps like this
Code:
Private Sub CommandButton1_Click()
Dim lr As Long      'last row
With Sheets("Sheet1")
    lr = .Range("B:C").Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
    .Range("B19:C" & lr).ClearContents
End With
End Sub
 
Consider adding a condition to the ClearContents line to prevent stuff being deleted above row 19 (for example, if you click the button twice):
Code:
If lr >= 19 Then .Range("B19:C" & lr).ClearContents
 
Back
Top