【问题标题】:Nested if function in VBAVBA中的嵌套if函数
【发布时间】:2019-02-15 11:55:08
【问题描述】:

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

如果 K= Business 且 E= null 高亮E

如果 K= Business 且 F= null 高亮 F

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

Sub business() 
    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

【问题讨论】:

  • edit 使用引发错误的代码提出问题。
  • 这不需要 VBA - 您可以使用条件格式来做到这一点。
  • 所以我想要一个到目前为止我得到的代码 Sub business() 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
  • 您将abc 设置为数组,然后在If 语句中测试它们,就好像它们是单独的值一样。只需在 E 列中放置一个条件格式,在 F 列中放置一个条件格式 - 例如 =AND(K2="Email",E2="")=AND(K2="Email",F2="")
  • 感谢您的回复。但我将此代码添加为大宏的一部分,这就是为什么我要寻找 vba 代码而不是条件格式。

标签: excel vba if-statement nested


【解决方案1】:

你可以避免循环:

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

【讨论】:

    猜你喜欢
    • 2019-05-16
    • 2019-06-18
    • 2017-03-06
    • 2016-04-23
    • 2015-03-14
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多