简体   繁体   中英

How to incorporate Not IsBlank into VBA code?

The code below works by copying rows with "Yes" in the M column into another sheet. I'm trying to find a way to also add the criteria that this will only work if column K is not blank (ie, text needs to be in column K first). I'm struggling to incorporate Not IsBlank or Not IsEmpty into this. Can anyone help please?

Sub Worksheet_Change(ByVal Target As Range)

    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("L:T")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then

        Application.ScreenUpdating = False

        Dim lastrow As Long

        lastrow = Sheets("New Refs").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

        Dim x As Long
        x = 4
        Dim rng As Range
        For Each rng In Sheets("New Refs").Range("M4:M" & lastrow)
            If rng = "Yes" Then
                rng.EntireRow.Copy Sheets("ASD 5P").Cells(x, 1)
                x = x + 1
            End If
        Next rng

        Application.ScreenUpdating = True
    End If

End Sub

Change :

If rng = "Yes" Then

To:

If rng = "Yes" And Trim(rng.Offset(, -2).Value2) <> "" Then

Note : I like to add Trim to make sure not to include cells with spaces only

The Cells() accepts string parameters as well for a column, thus concerning "K", it is a bit easier and more understanding if you use it:

If rng.Value2 = "Yes" And Trim(Cells(rng.Row, "K")) <> vbNullString Then

.Value2 is the real, unformated value of the cell and in this case it may be a good practice. The vbNullString is pretty much the same as "" , with the difference that a pointer would be used for the comparison, thus in theory it should be slightly faster.

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