我正在寻求一些VBA的帮助。
假设我有一系列单元格(B4:B12),所以如果我在该范围内的单元格中输入数据,我想清除相同范围内的所有单元格,除了我输入数据的单元格。因此,我只能在1个单元格中包含该范围内的数据。
因此,如果B5有数据并且我在B7中输入了数据,那么B5会清除,那么如果我在B10中输入数据,则B7会清除...
我希望有一个解决方案,因为我一直试图找到过去几个小时的答案。
答案 0 :(得分:0)
我会这样做:
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
答案 1 :(得分:0)
或者您可以在相关的工作表代码窗格
中使用工作表事件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