2016-05-13 107 views
1

我寫了這段代碼。我不明白爲什麼我得到錯誤:End If without block如果End If without block如果錯誤

Sub mytest() 

Dim i As Integer 
Dim s As Integer 
Dim j As Integer 
Dim p As Integer 
Dim k As Integer 
s = 0 

With Worksheets("mysheet") 
.Range("B28:B75").Select 

For i = 28 To 75 
     If Cells(i, 2).Value > 0 Then Cells(i, 2).Interior.Color = RGB(255, 255, 255) 
     s = s + 1 
     End If 
Next i 

.Range("A28:A75").Select 

For j = 28 To 75 

    If Cells(i, 2).Value = 0 Then Cells(i, 2).Interior.Pattern = xlPatternLightDown 
    Cells(i, 2).Interior.Color = RGB(255, 255, 255) 
    End If 

Next j 

p = 75 - s 
For k = 1 To s 
    Cells(s + k, 1).Interior.Color = RGB(18, 0, 0) 
Next k 

End With 

End If子句wasnt省略。我不明白爲什麼我得到錯誤

+1

嘗試在'Then'後面移動語句 –

+1

請注意,您的錯誤不是'Block If without End If',而是'End If without Block If'。您沒有缺少'End If',您有太多;)(請參閱下面的宏人或[此答案](http://stackoverflow.com/a/22580564/5350831)的答案)。 –

回答

1

在新行上的Then之後移動語句。恕我直言,VBA期望單行聲明,如果您在代碼之後使用它,則下一行代碼不帶end if會引發此錯誤。我還建議您閱讀有關VBA here的更多信息,以獲得更好的範圍和單元規格。

但你的錯誤使用像這樣

Sub mytest() 

Dim i As Integer 
Dim s As Integer 
Dim j As Integer 
Dim p As Integer 
Dim k As Integer 
s = 0 

With Worksheets("mysheet") 
.Range("B28:B75").Select 

For i = 28 To 75 
     If Cells(i, 2).Value > 0 Then 
     Cells(i, 2).Interior.Color = RGB(255, 255, 255) 
     s = s + 1 
     End If 
Next i 

.Range("A28:A75").Select 

For j = 28 To 75 

    If Cells(i, 2).Value = 0 Then 
    Cells(i, 2).Interior.Pattern = xlPatternLightDown 
    Cells(i, 2).Interior.Color = RGB(255, 255, 255) 
    End If 

Next j 

p = 75 - s 
For k = 1 To s 
    Cells(s + k, 1).Interior.Color = RGB(18, 0, 0) 
Next k 

End With 
4

如果您在一行寫的。如果這樣的語句:

If Foo = Bar Then FooBar() 

你並不需要使用End If因爲動作是在同一行執行的,所以聲明的結尾是暗示(編譯器知道任何東西在Then之後的同一行是有條件的,所以你不需要告訴它你的條件c在哪裏ODE結束)

如果放置在單獨一行的操作:

If Foo = Bar Then 
    FooBar() 
End If 

然後,你必須明確說不出哪裏條件代碼通過使用End If結束編譯器因爲沒有別的辦法它知道。