简体   繁体   English

Excel VBA - 遍历列并验证

[英]Excel VBA - Loop through column and validate

I'm trying to formulate VBA code in Excel to loop through column D and check if the word 'Incomplete' is present in a cell.我正在尝试在 Excel 中制定 VBA 代码以遍历 D 列并检查单元格中是否存在“不完整”一词。 If 'Incomplete' is present in any cell in column D AND the cell in the same row in column G is blank , then a message box will pop up.如果 D 列中的任何单元格中存在“不完整”且 G 列中同一行中的单元格为空白,则会弹出一个消息框。

I initially came up with this:我最初想出了这个:

If Range("D12").Value = "Incomplete" And Range("G12").Value = "" Then MsgBox ("Please add a comment in G12")
If Range("D13").Value = "Incomplete" And Range("G12").Value = "" Then MsgBox ("Please add a comment in G13")
If Range("D14").Value = "Incomplete" And Range("G12").Value = "" Then MsgBox ("Please add a comment in G14")
If Range("D15").Value = "Incomplete" And Range("G12").Value = "" Then MsgBox ("Please add a comment in G15")
If Range("D16").Value = "Incomplete" And Range("G12").Value = "" Then MsgBox ("Please add a comment in G16")
If Range("D17").Value = "Incomplete" And Range("G12").Value = "" Then MsgBox ("Please add a comment in G17")

And so on..

But this is clearly inefficient so I tried to create an automated process:但这显然效率低下,所以我尝试创建一个自动化流程:

Public Sub Validate()

Dim i As Long

For i = 4 To Rows.Count

Next i

If Cells(i, 4).Value = "Incomplete" And IsEmpty(Cells(i, 7).Value) Then
    MsgBox ("Please add a comment corresponding to an Incomplete task")

End If

End Sub

This throws a run-time error '1004'Application-defined or object-defined error.这会引发运行时错误“1004”应用程序定义或对象定义错误。 I've also realised that this will not check if the cell in the same row is blank.我也意识到这不会检查同一行中的单元格是否为空白。

Any help to resolve this would be much appreciated.任何解决此问题的帮助将不胜感激。

Many thanks非常感谢

As mentioned in the comments you logic code is not in the loop, and you will spam the user with message boxes.正如评论中提到的,您的逻辑代码不在循环中,您将使用消息框向用户发送垃圾邮件。 I would concatenate the cells into a single message, and fix the logic as below:我会将单元格连接成一条消息,并修复如下逻辑:

Sub Validate()

    Dim rng As Range, cell As Range
    Dim message As String

    Set rng = Range("D12:D36") 'set your range here

    For Each cell In rng
        If LCase(cell.Value) = "incomplete" And cell.Offset(0, 3).Value = "" Then
            'concatenate a message rather than spamming
            If message = "" Then
                message = "Please add a comment corresponding to an Incomplete task for cell(s) " & vbCrLf & cell.Offset(0, 3).Address
            Else
                message = message & vbCrLf & cell.Offset(0, 3).Address
            End If
        End If
    Next cell
    
    'show a message if any are invalid
    If message <> "" Then
        MsgBox (message)
    End If


End Sub 

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

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