如何将Not IsBlank合并到VBA代码中?

时间:2018-03-12 11:31:58

标签: vba excel-vba excel

以下代码的工作原理是复制行"是"在M列成另一张纸。我试图找到一种方法来添加标准,只有当列K不为空时才会起作用(即,文本需要先在列K中)。我努力将Not IsBlank或Not IsEmpty纳入其中。有人可以帮忙吗?

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

2 个答案:

答案 0 :(得分:1)

更改:

If rng = "Yes" Then

要:

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

注意:我想添加Trim以确保不包含仅包含空格的单元格

答案 1 :(得分:0)

Cells()接受字符串参数以及列,因此关于“K”,如果您使用它,它会更容易理解:

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

.Value2是细胞真实的,未格式化的值,在这种情况下,它可能是一种很好的做法。 vbNullString""几乎相同,区别在于指针将用于比较,因此理论上它应该稍快一些。