首页 > 解决方案 > 我的 VBA IF 语句生成编译错误

问题描述

我的代码有问题,我似乎找不到它,所以我需要另一双眼睛,我想我要盲用 VBA。

这是我的代码非常简单,如果有人在做更高级别,那么 3 列将显示为灰色并且不适用,因为他们不会在 D、F 和 G 列中为这些模块获得任何结果。如果没有做更高级别,那么它将是相反的,他们不会在 B、C 和 E 列中获得模块的结果。有 28 名学员,因此它需要适用于所有行。

当前代码如下:

Private Sub Update()
    Dim Course As String
    Dataset = Range("A").Value

    If Course = "Higher" Then
        Range("D").Value = "N/A"
        Range("F").Value = "N/A"
        Range("G").Value = "N/A"
        Range("D,F,G").Select

        With Selection.Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .ThemeColor = xlThemeColorDark1
            .TintAndShade = -0.249977111117893
            .PatternTintAndShade = 0
    Else
            Range("B").Value = "N/A"
            Range("C").Value = "N/A"
            Range("E").Value = "N/A"
            Range("B,C,E").Select

            With Selection.Interior
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
                .ThemeColor = xlThemeColorDark1
                .TintAndShade = -0.249977111117893
                .PatternTintAndShade = 0
    End If
            End With

End Sub

但是,我收到一个编译错误,提示“Else without and If”。据我所知,声明了所有变量,该IF语句的结构正确。

有什么想法吗?

标签: excelvbaif-statement

解决方案


试试这个:

Private Sub Update()
    Dim Course As String
    Dataset = Range("A").Value

    If Course = "Higher" Then
        Range("D").Value = "N/A"
        Range("F").Value = "N/A"
        Range("G").Value = "N/A"
        Range("D,F,G").Select

        With Selection.Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .ThemeColor = xlThemeColorDark1
            .TintAndShade = -0.249977111117893
            .PatternTintAndShade = 0
        End With
    Else
            Range("B").Value = "N/A"
            Range("C").Value = "N/A"
            Range("E").Value = "N/A"
            Range("B,C,E").Select

            With Selection.Interior
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
                .ThemeColor = xlThemeColorDark1
                .TintAndShade = -0.249977111117893
                .PatternTintAndShade = 0
            End With
    End If

End Sub

如果归结为:

If ... Then
  ...
  With ...     'Start the first With-clause
    ...
  End With     'End the first With-clause
Else           'All With-clauses need to be closed before you can go here
  ...
  With ...     'Start the second With-clause
    ...
  End With     'End the second With-clause
End If         'All With-clauses needed be closed before you can go here.

推荐阅读