简体   繁体   English

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

[英]How to incorporate Not IsBlank into VBA code?

The code below works by copying rows with "Yes" in the M column into another sheet. 下面的代码通过将M列中带有“是”的行复制到另一张工作表中。 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). 我正在尝试找到一种方法来添加仅在K列不为空时才起作用的条件(即,文本必须首先在K列中)。 I'm struggling to incorporate Not IsBlank or Not IsEmpty into this. 我正在努力将Not IsBlank或Not IsEmpty合并到其中。 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 注意 :我喜欢添加Trim以确保不只包含空格的单元格

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: Cells()接受一列的字符串参数,因此涉及“ K”,如果使用它,则更容易理解。

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. .Value2是单元格的真实, .Value2格式化的值,在这种情况下,这可能是一个好习惯。 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. vbNullString""几乎相同,不同之处在于将使用指针进行比较,因此从理论上讲它应该稍快一些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM