简体   繁体   中英

VBA to clear excel cells

Range("A4:A29").Select
Selection.ClearContents
Range("A34:A59").Select
Selection.ClearContents
Range("A64:A89").Select
Selection.ClearContents
Range("A94:A119").Select
Selection.ClearContents
Range("A124:A149").Select
Selection.ClearContents
Range("A154:A179").Select
Selection.ClearContents
Range("A184:A209").Select
Selection.ClearContents
Range("A1").Select

I did the above coding to clear some boxes in excel, but it does not give me flexibility over range of boxes, what I want is to clear out any filled boxes in column A but if x mod 30 equals to zero to skip the next 3 and so on. I have used a similar code to fill up the boxes, see below:

With RegExp
    .Pattern = "\bT[0-9A-Z\(\)\-]+"
    .Global = True
    .IgnoreCase = False
    Set matches = .Execute(txt)
End With                                        

For Each Match In matches
    If x Mod 30 = 0 Then
        x = x + 4
    End If
    Cells(x, 1) = Match
    x = x + 1
    Cells(x, 1) = Match
    If x Mod 30 <> 0 Then
        x = x + 1
    End If
Next

If anyone could help me that would be great! Thanks

It's a bad idea (performance-wise) to first select the cell and then use Selection.ClearContents

Try this principle:

Range(Cells(x, 1), Cells(x + 29, 1)) = ""

This clears the contents of all Cells between x,1 and x+29,1

For your purpose it might be something like this (you might have to tweek the details because they are not clear from your post):

For x = 0 to 9 ' repeat however many times you want
    startingRow = x * 33 + 1
    Range(Cells(startingRow, 1), Cells(startingRow + 28, 1)) = ""
Next

I got it. Thanks @E.Villager

Private Sub CommandButton2_Click()
Dim lRow As Long
 Dim lCol As Long

 lRow = Cells(Rows.Count, 1).End(xlUp).Row

 For x = 4 To lRow

  If x Mod 30 = 0 Then
               x = x + 4
          End If
                Cells(x, 1) = ""

 Next

 End Sub

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