简体   繁体   中英

VBA code to clear contents of cell A and B if cells C blank when macro runs from another sheet

I am trying to clear extra cells of column A and B if find blank cells in column C of sheet named Sold and Macro runs from Sheet named Invoice .

I got below code from a helping site but cannot get my desired result.Below attached is the screenshot of desired output

Sum Clear()

Dim g As Long
For g = 2 To ActiveSheet.UsedRange.Rows.Count
If Cells(g, "C").Value = "" Then
Cells(g, "A").ClearContents
Cells(g, "B").ClearContents 

End If
Next
End Sum

想要的结果

Non VBA Way

you can put formula =IF(LEN(TRIM(C2))=0,"",POPULATETHISCELL) in the cells A and B where you can replace POPULATETHISCELL with whatever you are trying to get there. For example, populating today's date.

VBA Way

  1. Work with Objects . Avoid the use of ActiveWorkbook/Activesheet/Selection etc as show HERE
  2. Avoid the use of UsedRange . Find last row as shown HERE and then loop through it.
  3. Instead of clearing ranges twice, you can clear it in one go as shown below

Is this what you are trying?

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim lastrow As Long
    Dim i As Long

    Set ws = ThisWorkbook.Sheets("Sold")

    With ws
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            lastrow = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row

            For i = 2 To lastrow
                If Len(Trim(.Range("C" & i).Value)) = 0 Then _
                .Range("A" & i & ":B" & i).ClearContents
            Next i
        End If
    End With
End Sub

You need to include the name of the sheet.

Sub Clear()
Dim g As Long
With ActiveWorkbook.Sheets("Sold")
    For g = 2 To .UsedRange.Rows.Count
        If .Cells(g, "C").Value = "" Then
            .Cells(g, "A").ClearContents
            .Cells(g, "B").ClearContents
        End If
    Next
End With
End Sub

Try something like :

Sub Sample()
 '============ Init ================
 Dim Ws_Sold As Worksheet
 Set Ws_Sold = Sheets("Sold")
 Dim count As Integer
 count = 1
 Dim lastrow As Long
 lastrow = Ws_Sold.Cells.SpecialCells(xlCellTypeLastCell).Row 
 'give number of the last cell not empty

 '============ loop================
 While (count < lastrow + 1)
    If Ws_Sold.Cells(count, 3).Value = "" Then
        Ws_Sold.Cells(count, 1).ClearContents
        Ws_Sold.Cells(count, 2).ClearContents    
    End If
    count = count + 1
 Wend 

End Sub

Have a nice day !

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