我的 VBA IF 语句生成编译错误

时间:2021-07-13 10:52:41

标签: excel vba if-statement

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

这是我的代码,如果有人在做更高级别的工作,那么 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 语句的结构正确。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

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.

答案 1 :(得分:0)

您有 2 个 With 语句,而只有 1 个 End With

将您的 With Selection.Interior 移到第一个 If 上方并删除第二个 With

将最后一个 End With 移到 End If 上方。