简体   繁体   中英

VBA If cell (or range) on sheet1 contains any value then clear content of cell range on sheet 2

I am trying to achieve something which would be quite simple for you guys but proving a bit difficult for myself as beginner.

I am try to create script for following example:

"If Cells A1:A4 on sheet1 contain ANY value (text or int) then clear A1:A4 on sheet2"

I tried to construct few scripts but all failed.

Many thanks!

Try this

Sub Clear()
 If Not IsEmpty("A1") And Not IsEmpty("A2") And Not IsEmpty("A3") And Not IsEmpty("A4") Then
    Range("A1:A4").Clear
 End If
End Sub

How about:

Sub ClearCell()
    Dim r As Range

    For Each r In Sheets("Sheet1").Range("A1:A4")
        If r.Value <> "" Then Sheets("Sheet2").Range(r.Address).Clear
    Next r
End Sub

This assumes you need the check to be cell-by-cell.

Here's a one liner, the cell value is counted when it is an Empty String.

    Public Sub ClearRange()
        If Application.WorksheetFunction.CountIf(Range("a1:a4"), "<>") > 0 Then Range("a1:a4").ClearContents
    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