IF语句在VBA中更改不正确的非数值的格式

时间:2016-10-13 09:06:51

标签: excel vba excel-vba

我有这个代码:

 With .Cells(i, 6)
        If .NumberFormat <> "0.0%" Then
            .NumberFormat = "0.0%"
            If .Value2 <> vbNullString And IsNumeric(.Value2) Then .Value = .Value / 100
                If .Value2 = vbNullString Then
                    .Value = "---"
                    .HorizontalAlignment = xlRight
                End If
                    If .Value >= 0.9 Then
                        .Interior.Color = RGB(237, 67, 55)
                        .Font.Color = vbWhite
                    End If
        Else
            .Value = 0
        End If
    End With

代码的作用是在列中查找超过90%的值,如果是这样,它将单元格内部格式化为红色,将字体格式化为白色。但我在同一列上有一些没有任何值的单元格,因此我希望单元格中有“---”使其看起来整洁,但当我运行代码时,单元格为“---” “在它中也形成了红色填充和白色字体。 我想要的是那些单元格保留原始格式。

我写了这个if语句,但不知道在“THEN”部分之后要写什么:

IF .Value = "---" Then 

我是菜鸟!谢谢你的帮助!

2 个答案:

答案 0 :(得分:3)

这会回答吗?

 With .Cells(i, 6)
        If .NumberFormat <> "0.0%" Then
            .NumberFormat = "0.0%"
            If .Value <> vbNullString And IsNumeric(.Value2) Then 
                .Value = .Value / 100
                if .Value >= 0.9 Then
                    .Interior.Color = RGB(237, 67, 55)
                    .Font.Color = vbWhite
                End If

            elseIf .Value = vbNullString Then
                    .Value = "---"
                    .HorizontalAlignment = xlRight
            Else
                stop 'I think you forgot this case
            end if
        Else
            .Value = 0
        End If
    End With

编辑:我添加了@Zac的建议:使用红色的条件格式。

答案 1 :(得分:1)

确定测试的优先顺序,这应该可以解决问题:

With .Cells(i, 6)
    If .NumberFormat <> "0.0%" Then
        .NumberFormat = "0.0%"
        If .Value2 <> vbNullString Then
            If IsNumeric(.Value2) Then .Value2 = .Value2 / 100
            If .Value2 >= 0.9 And .Value <> "---" Then
                .Interior.Color = RGB(237, 67, 55)
                .Font.Color = vbWhite
            End If
        Else
            .Value = "---"
            .HorizontalAlignment = xlRight
        End If
    Else
        .Value = 0
    End If
End With