VBA仅为具有False值的单元格设置条件格式

时间:2017-02-20 09:08:10

标签: excel vba excel-vba

我使用VBA将条件格式应用于工作表,如果内容为&#34,则设置背景颜色和正面颜色;错误":

Sub Formatting()

    Sheets("File").Cells.FormatConditions.Delete

    With Range("N2:N2000").FormatConditions.Add( _
        Type:=xlExpression, _
        Formula1:="=$N2=FALSE")
        .Interior.Color = RGB(255, 239, 239)
        .Font.Color = RGB(97, 0, 0)
    End With
End Sub

但是,空白单元格也会变红。

如何仅将条件格式应用于带有" False"的单元格值?

2 个答案:

答案 0 :(得分:2)

尝试将其匹配为文字:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
    let item = sections[indexPath.section].items[indexPath.row]
    if sections[indexPath.section].isMultiple {
        //For multiple selection
        if item.selected {
            cell.accessoryType = .checkmark //Or make label red
        }
        else {
            cell.accessoryType = .none //Or make label white
        }
    }
    else {
        //For single selection
        if item.selected {
            cell.accessoryType = .checkmark //Or make label red
        }
        else {
            cell.accessoryType = .none //Or make label white
        }
    }
    cell.textLabel?.text = sections[indexPath.section].items[indexPath.row].name

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if sections[indexPath.section].isMultiple {
        //For multiple selection
        let item = sections[indexPath.section].items[indexPath.row]
        item.selected = !item.selected
        sections[indexPath.section].items[indexPath.row] = item
        self.tableView.reloadRows(at: [indexPath], with: .automatic)
    }
    else {
        //For multiple selection
        let items = sections[indexPath.section].items

        if let selectedItemIndex = items.indices.first(where: { items[$0].selected }) {
            sections[indexPath.section].items[selectedItemIndex].selected = false
            if selectedItemIndex != indexPath.row {
                sections[indexPath.section].items[indexPath.row].selected = true
            }
        }
        else {
            sections[indexPath.section].items[indexPath.row].selected = true
        }
        self.tableView.reloadSections([indexPath.section], with: .automatic)
    }
}

答案 1 :(得分:2)

首先,请确保Range("N2:N2000")Sheets("File")完全合格。

其次,如果您只想将格式应用于单词“FALSE”,则单元格内没有额外字符使用TextOperator:=xlEqual,否则请使用TextOperator:=xlContains

<强>代码

Option Explicit

Sub Formatting()

    With Sheets("File")
        .Cells.FormatConditions.Delete

        With .Range("N2:N2000").FormatConditions.Add( _
            Type:=xlTextString, String:="FALSE", TextOperator:=xlEqual)
            .Interior.Color = RGB(255, 239, 239)
            .Font.Color = RGB(97, 0, 0)
        End With
    End With

End Sub