简体   繁体   中英

VBA, ClearContents in columns only where range = string

I want to clear contents in a specified column(s) where col A = "stack" . I don't want to use range("A2:A1000") as this can change.

having some trouble here, not sure if I need to loop through each row, can anyone help me start this off.

Sub Clear()

Dim stack As Range
stack= Sheets("database").Range("A2").Offset("stack", 0).endxlup.Select
Range("CJ:CW").stack.ClearContents

End Sub

I am going to take a punt on what you have described rather than the code.

I want to clear contents in a specified column(s) where col A = "stack". I don't want to use range("A2:A1000") as this can change.

I will take that as being dynamically determine the end row in column A and then loop from A2 to it. If column A value, for a given cell, is "stack" then clear the contents of CJ:CW in the same row.

Option Explicit
Public Sub ClearCells()
    Dim mainRange As Range, rng As Range
    Application.ScreenUpdating = False
    With ThisWorkbook.Worksheets("database")
        Set mainRange = .Range("A2:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
        For Each rng In mainRange.SpecialCells(xlCellTypeConstants)
            If rng.Value = "stack" Then
                rng.Offset(, 87).Resize(1, 14).ClearContents
            End If
        Next
    End With
    Application.ScreenUpdating = True
End Sub

Array version:

Option Explicit
Public Sub ClearCells()
    Dim mainRange As Range, arr(), i As Long, j As Long
    Application.ScreenUpdating = False
    With ThisWorkbook.Worksheets("database")
        Set mainRange = .Range("A2:CW" & .Cells(.Rows.Count, "A").End(xlUp).Row)
        arr = mainRange.Value
        For i = LBound(arr, 1) To UBound(arr, 1)
            If arr(i, 1) = "stack" Then
                 For j = 1 To 14
                     arr(i, 87 + j) = vbNullString
                 Next
            End If
        Next
        mainRange = arr
    End With
    Application.ScreenUpdating = True
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