如果则语句在VB Excel中编译错误

时间:2020-11-08 06:34:33

标签: excel vba

这是我的vba代码,遇到上述错误,但我无法理解问题所在。

Sub If_Loop()
Dim cell As Range

For each cell in Range(“Sheet3”)

If cell.Value > 4400 and cell.Value < 8500 Then cell.Interior.Color = VBA.ColorConstants.vbGreen

End If
Next Cell

End Sub

2 个答案:

答案 0 :(得分:1)

您是否有一个名为“ Sheet3”的命名范围?我猜那是您的工作表名称?

另外,您使用的是单行If-Then,因此不需要End If。 可能更清楚地将其拆分:

Sub If_Loop()
    Dim cell As Range
    
    For each cell in Sheets("Sheet3").Range("A1:E100").Cells 'for example
        If cell.Value > 4400 and cell.Value < 8500 Then 
             cell.Interior.Color = vbGreen
        End If
    Next Cell
End Sub

答案 1 :(得分:0)

当您的from itertools import combinations fd = pd.DataFrame(index = combinations(df.index,2)) fd['Ccom'] = list(combinations(df.C,2)) fd['Wcom'] = list(combinations(df.W,2)) fd['Lcom'] = list(combinations(df.L,2)) fd['Dcom'] = list(combinations(df.D,2)) fd.head() Ccom Wcom Lcom Dcom ('A1', 'A2') (82.0, 19.0) (78.0, 99.0) (1100.0, 9520.0) (3.0, 3.0) ('A1', 'A3') (82.0, 25.0) (78.0, 42.0) (1100.0, 1700.0) (3.0, 7.0) ('A1', 'A4') (82.0, 93.0) (78.0, 37.0) (1100.0, 1700.0) (3.0, 7.0) ('A1', 'A5') (82.0, 9.2) (78.0, 0.44) (1100.0, 510.0) (3.0, 7.0) ('A2', 'A3') (82.0, 52.0) (78.0, 0.042) (1100.0, 1100.0) (3.0, 17.2) 语句在一行上时,就像这样

If

您不需要If cell.Value > 4400 and cell.Value < 8500 Then cell.Interior.Color = VBA.ColorConstants.vbGreen

您只需要End If就可以了

End If

检查If...Then...Else statement文档。

请注意以下说明:

您可以使用单行形式(第一种语法)来简短,简单 测试。但是,块形式(第二种语法)提供了更多的结构 和灵活性比单行形式更容易实现 读取,维护和调试。

我建议您重构代码并使用块形式(即,多行与If cell.Value > 4400 and cell.Value < 8500 Then cell.Interior.Color = VBA.ColorConstants.vbGreen End If

相关问题