用于标识单元格是否包含循环的VBA代码

时间:2017-05-12 02:57:01

标签: excel vba excel-vba

所以目前我正在尝试提出一个if语句。基本上如果A3有任何文本值,我希望它等同于真棒。我想在最后一栏中记住这个命令。

Sub Criteria

    If Range("A2") = "Feedback" And Range("A3") = "**" Then
        Range("A1") = "Awesome"
    Else
        Range("A1") = ""
    End If

End sub

(这是我提出的代码可以帮助我让它更清洁/更快)

Sub Status()

    lastrow = Rows(Rows.Count).End(xlUp).Row

    For i = 2 To lastrow

        If Cells(i, 1) = "Onsite" And Not IsEmpty(Cells(i, 2)) Then
            Cells(i, 3) = "Feedback"
        Else
            If Cells(i, 1) = "Phone" And Not IsEmpty(Cells(i, 2)) Then
                Cells(i, 3) = "Feedback"
            Else
                If Cells(i, 1) = "Phone" And IsEmpty(Cells(i, 2)) Then
                    Cells(i, 3) = "Pending Next Step"
                Else
                    If Cells(i, 1) = "Onsite" And IsEmpty(Cells(i, 2)) Then
                        Cells(i, 3) = "Pending Decision"
                    End If
                End If
            End If
        End If

    Next i

End Sub

1 个答案:

答案 0 :(得分:0)

尝试使用Option Explicit同时设置工作表,以免错误工作表上运行代码或避免错误

Option Explicit
Public Sub Status()
    Dim Sht As Worksheet
    Dim rng As Range

    Set Sht = ThisWorkbook.Sheets("Sheet1")

    For Each rng In Sht.Range("A2", Sht.Range("A9999").End(xlUp))
        Debug.Print rng.Address ' print on immed win
        DoEvents ' For Debuging

        If rng.Value = "Onsite" And rng.Offset(0, 1).Value > 0 Then
            rng.Offset(0, 2).Value = "Feedback"
        ElseIf rng.Value = "Onsite" And rng.Offset(0, 1).Value = "" Then
            rng.Offset(0, 2).Value = "Pending Decision"
        End If

        If rng.Value = "Phone" And rng.Offset(0, 1).Value > 0 Then
            rng.Offset(0, 2).Value = "Feedback"
        ElseIf rng.Value = "Phone" And rng.Offset(0, 1).Value = "" Then
            rng.Offset(0, 2).Value = "Pending Next Step"
        End If

    Next

    Set Sht = Nothing
    Set rng = Nothing
End Sub

<强> Range.Offset Property (Excel)

语法:expression.Offset(RowOffset,ColumnOffset)

  

返回 Range 对象,该对象表示偏离指定范围的范围。