简体   繁体   中英

Excel VBA - clear cells above and below cell with text

I'm looking for some help please with some VBA.

Let's say I have a range of cells (B4:B12), so if I input data in a cell within the range I would like to clear all cells in the same range except for the cell in which I inputed the data. So that I can only have 1 cell with data in the range.

So if B5 had data and I inputed data in B7 then B5 would clear, then if i entered data in B10 then B7 would clear...

I hope there is a solution as I have been trying to find an answer for the past couple of hours.

I would do it this way:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

Set myRange = Sh.Range("B4:B12")

'set the current cell/address/value so we don't lose them when the range is cleared
Set cell = Sh.Range(Target.address)    
value = Target

'disable/enable so this isn't called every time a cell is cleared
'clear the range then reset the to entered value
If Not Intersect(Target, myRange) Is Nothing Then
    Application.EnableEvents = False
    myRange.Clear
    cell.value = value
    Application.EnableEvents = True
End If

End Sub

Or you could use worksheet event to bevplaced in the relevant worksheet code pane

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim myVal As Variant

    With Range("B4:B12") ‘reference your range
        If Not Intersect(Target, .Cells) Is Nothing And Target.Count = 1 Then ‘ if changed range is one cell within the referenced one
            myVal = Target.Value ‘store changed cell value
            Application.EnableEvents = False
            .ClearContents ‘ clear the content of referenced range
            Target.Value = myVal ‘ write changed cell value back
            Application.EnableEvents = True
        End If
    End With 
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