清除后剩余的Excel单元格值

时间:2018-07-30 15:51:32

标签: excel vba excel-vba

我正在使用VBA清除excel文件中的某些单元格,但是当清除它们时,值仍然存在。当我单击单元格时,值消失了,但是一旦代码中的单元格被清除,我就需要它来执行。编辑:根据要求,更多代码。直到我按建议将其值设置为空,这些单元格仍然不会清空,直到我单击它们。

Private Sub Update(Target As Range, EventTarget As Range)
On Error GoTo ErrorHandling
Application.EnableEvents = False
Dim CurrDevice As String
Dim CurrPort As String
Dim ConcatInfo As String

CurrDevice = Range("B" & Target.Row).Value
CurrPort = Range("C" & Target.Row).Value
ConcatInfo = CurrDevice + CurrPort

Dim TargetRange As Range
Set TargetRange = Range("R2:R" & EventTarget.Row - 1).Find(ConcatInfo, LookIn:=xlValues)

If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then
    'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents
     Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty
    End If
End If

Set TargetRange = Nothing
Set TargetRange = Range("R" & (EventTarget.Row + 1), Range("R" & (EventTarget.Row + 1)).End(xlDown)).Find(ConcatInfo, LookIn:=xlValues)
If Not TargetRange Is Nothing And Not TargetRange.Row = EventTarget.Row Then
    'Range("F" & TargetRange.Row, "P" & TargetRange.Row).ClearContents
    Range("F" & TargetRange.Row, "P" & TargetRange.Row).Value = Empty

End If

Exit Sub

ErrorHandling:     Application.EnableEvents =真 结束

2 个答案:

答案 0 :(得分:0)

尝试以下代码:

Sub TestMe()
    Worksheets("NameOfWorksheet").Range("A" & 1, "Z" & 10).ClearContents
End Sub

然后用1缓慢更改10TargetRange.Row,然后查看其是否有效。 TargetRange应该定义为如下范围:

Dim TargetRange as Range

并设置为以下范围:

Set TargetRange = Worksheets(1).Range("A19")

答案 1 :(得分:0)

要清除单元格,可以将其分配为空:

worksheet.Cells(1, 1).Value = Empty