在VBA中嵌套if函数

时间:2018-09-11 03:05:44

标签: excel vba if-statement nested

所以我想要一个可以执行以下代码的代码...

如果K =商业且E =空 突出显示E

如果K =商业且F =空 突出显示F

每次我尝试说类型不匹配或对象错误

Sub bussiness() 
    Dim a As String 
    Dim b As String 
    Dim c As String

    Set a.Value = Range("K2:K300") 
    Set b.Value = Range("E2:E300") 
    Set c.Value = Range("F2:F200")

    If a = "Email" And b = "" Or c = "" Then 
        Cell.Interior.ColorIndex = 3 
    Else
        Cell.Interior.ColorIndex = 0 
    End If 
End Sub

This is the snippet of my worksheet

2 个答案:

答案 0 :(得分:0)

不能100%确定您要做什么,但这可能是朝着正确的方向迈进的

编辑:代码现在突出显示请求的行。

Sub Business()
    Dim a As Range
    Dim b As Range
    Dim c As Range

     Set a = Range("K2:K300")
     Set b = Range("E2:E300")
     Set c = Range("F2:F200")

    Dim cell As Range

    For Each cell In a
        If cell.Value = "Business" And cell.Offset(0, 1).Value = "" And cell.Offset(0, 2).Value = "" Then
            cell.Interior.ColorIndex = 3
            cell.Offset(0, -6).Interior.ColorIndex = 3
            cell.Offset(0, -5).Interior.ColorIndex = 3
        End If
    Next cell
End Sub

enter image description here

答案 1 :(得分:0)

您可以避免循环:

With Range("A1").CurrentRegion.Columns(11) ' reference your database (assuming header row is row 1, starts at column 1 and no header is blank)
    If WorksheetFunction.CountIf(.Cells, "Business") > 0 Then 'if any "business" occurrence
        .Replace what:="Business", replacement:=1, lookat:=xlWhole ' mark "business" row with a number
        On Error Resume Next
        With Intersect(.SpecialCells(xlCellTypeConstants, xlNumbers).EntireRow, .Offset(, -6)) ' reference "marked" rows cell in column E (6th column left of column K)
            .SpecialCells(xlCellTypeBlanks).Interior.Color = vbRed 'mark any referenced range blank cell in red
            .Offset(, 1).SpecialCells(xlCellTypeBlanks).Interior.Color = vbRed 'mark any referenced range 1 column right blank cell in red
        End With
        On Error GoTo 0
        .Replace what:=1, replacement:="Business", lookat:=xlWhole ' get "business" back in place
    End If
End With