簡體   English   中英

Excel VBA-用文本清除單元格上方和下方的單元格

[英]Excel VBA - clear cells above and below cell with text

我正在尋找一些VBA的幫助。

假設我有一個單元格范圍(B4:B12),因此,如果我在該范圍內的單元格中輸入數據,我想清除同一范圍內的所有單元格,但我要輸入數據的單元格除外。 這樣我只能有1個單元格的數據在范圍內。

因此,如果B5有數據並且我在B7中輸入了數據,則B5將清除,然后,如果我在B10中輸入了數據,則B7將清除...

我希望有一個解決方案,因為我在過去的幾個小時中一直在努力尋找答案。

我會這樣:

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

或者您可以使用工作表事件將其放置在相關的工作表代碼窗格中

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM