Ошибка в vba else without if ошибка

Здравствуйте. Наверное, напутала что-то с типами данных.. При выполнении данного макроса возникает ошибка «Else without if» :  

  Sub Macros()  
Dim i As Integer  
Dim j As Integer  
Dim x As Integer  
Dim y As Integer  
Dim A As Double  

  x = ActiveCell.Row  
y = ActiveCell.Column  
i = x  

  Do While ((ColorIndex(Cells(i, y))) <> 21)  
   Cells(i, y + 6).Value = Cells(i, y + 1).Value  
   Cells(i, y + 1).Formula = «=MID(RC[-1],SEARCH(«»??.??.????»»,RC[-1],1),10)»
   Cells(i, y + 1).NumberFormat = «m/d/yyyy»  
   Cells(i, y + 2).NumberFormat = «0»  
   Cells(i, y + 3).NumberFormat = «m/d/yyyy»  
   Cells(i, y + 3).Value = Cells(i, y + 1).Value + Cells(i, y + 2).Value  
   Cells(i, y + 4).NumberFormat = «m/d/yyyy»  
   Cells(i, y + 4).Formula = «=TODAY()»  
   Cells(i, y + 5).NumberFormat = «0»  
   Cells(i, y + 6).NumberFormat = «#,##0.00»  
   Cells(i, y + 7).NumberFormat = «#,##0.00»  
   Cells(i, y + 8).NumberFormat = «#,##0.00»  
   Cells(i, y + 9).NumberFormat = «#,##0.00»  
   Cells(i, y + 10).NumberFormat = «#,##0.00»  
   Cells(i, y + 11).NumberFormat = «#,##0.00»  
   Cells(i, y + 12).NumberFormat = «#,##0.00»  
   Cells(i, y + 13).NumberFormat = «#,##0.00»  
   Cells(i, y + 14).NumberFormat = «#,##0.00»  
   Cells(i, y + 5).Value = Cells(i, y + 4).Value — Cells(i, y + 3).Value  
   Cells(i, y + 2).Value = 30  
   A = Cells(i, y + 5).Value  
   If (A <= 0) Then Cells(i, y + 7).Value = Cells(i, y + 6).Value  
   Else: Cells(i, y + 7).Value = Cells(i, y + 16).Value  
   If ((A > 0) And (A <= 30)) Then Cells(i, y + 8).Value = Cells(i, y + 6).Value  
   Else: Cells(i, y + 8).Value = Cells(i, y + 16).Value  
   If ((A > 30) And (A)) Then Cells(i, y + 9).Value = Cells(i, y + 6).Value  
   Else: Cells(i, y + 9).Value = Cells(i, y + 16).Value  
   If ((A > 45) And (A <= 60)) Then Cells(i, y + 10).Value = Cells(i, y + 6).Value  
   Else: Cells(i, y + 10).Value = Cells(i, y + 16).Value  
   If ((A > 60) And (A <= 75)) Then Cells(i, y + 11).Value = Cells(i, y + 6).Value  
   Else: Cells(i, y + 11).Value = Cells(i, y + 16).Value  
   If ((A > 75) And (A <= 90)) Then Cells(i, y + 12).Value = Cells(i, y + 6).Value  
   Else: Cells(i, y + 12).Value = Cells(i, y + 16).Value  
   If (A > 90) Then Cells(i, y + 13).Value = Cells(i, y + 6).Value  
   Else: Cells(i, y + 13).Value = Cells(i, y + 16).Value  
   Cells(i, y + 14).Value = Cells(i, y + 8).Value + Cells(i, y + 9).Value + Cells(i, y + 10).Value + Cells(i, y + 11).Value + Cells(i, y + 12).Value + Cells(i, y + 13).Value  
Loop  
   j = y  
   i = x  
   Do While ((ColorIndex(Cells(i, y))) <> 21)  
       For j = y + 1 To 14  
           Cells(i, j).Interior.ColorIndex = ColorIndex(Cells(i, x))  
           If Cells(i, j).Interior.ColorIndex = 24 Then Cells(i, j).Value = Cells(x, y + 16).Value  
           End If  
       Next j  
   Loop  
   For j = 6 To 14  
       Summa_po_tsvetam (Cells(x, j))  
   Next j  
End Sub  

  Подскажите, пожалуйста, в чем моя ошибка?

I’m trying to run the following code, but I keep getting the Else without If Error in the first sub. The code is supposed to run through a column, open webpages if there is a url in the cell, then save the page info as a text file. If there is no url, then it just saves the text within that file as a text file. I can’t figure out how to change the syntax to get it to work.

Sub LoopOverB()

Dim myRow As Long

myRow = 10

While Worksheets("Input_Format_A").Cells(myRow, 2).value <> ""
    If InStr(1, Worksheets("Input_Format_A").Cells(myRow, 2).value, "http://", vbTextCompare) Then Call url_Test(Worksheets("Input_Format_A").Cells(myRow, 2).value, "C:mallettest" & Worksheets("Input_Format_A").Cells(myRow, 1).value & ".txt")
        myRow = myRow + 1
    Else
        Open "C:mallettest" & Worksheets("Input_Format_A").Cells(myRow, 1) & ".txt" For Append As #1
        Print #1, Worksheets("Input_Format_A").Cells(myRow, 2).value
        Close #1

        myRow = myRow + 1
    End If
Wend
End Sub


Sub url_Test(URL As String, Filename As String)

Dim FSO As Object
Dim ieApp As Object
Dim Txt As String
Dim TxtFile As Object

Set FSO = CreateObject("Scripting.FileSystemObject")
Set TxtFile = FSO.OpenTextFile(Filename, 2, True, -1)

Set ieApp = CreateObject("InternetExplorer.Application")
ieApp.Visible = True
ieApp.Navigate URL

While ieApp.Busy Or ieApp.ReadyState <> 4
    DoEvents
Wend

Txt = ieApp.Document.body.innerText
TxtFile.Write Txt
TxtFile.Close

ieApp.Quit

Set ieApp = Nothing
Set FSO = Nothing
End Sub

else without if error popup

What you’re seeing is a compile error that indicates that an Else (or ElseIf) keyword was not preceded by a correct If statement.

Meaning, the compiler found an Else statement (which it will highlight for the user) without seeing an If statement in the lines above it. This is an error because it violates the correct syntax of an If-Then-Else statement. The correct syntax is as follows:

For using the shorthand syntax for if statement that specifies a condition and an action (for when the condition is met):

If [Test Expression] Then [Action]

To use the standard syntax for an If statement that specifies a condition and an action (for when the condition is met) and an alternate action for when the condition is not met:

If [Test Expression] Then

[Action]

Else

[Alternate Action]

End if

For specifying more than one condition (and their actions):

If [Test Expression] Then

[Action]

ElseIf [Test Expression 2] Then

[Action 2]

Else

[Alternate Action]

End if

The compiling error “Else Without If” occurs when “If [Test Expression] Then “ is missing or written incorrectly. Let’s discuss the common causes of the error further in details below with examples.

Missing If Statement

When VBA compiler sees that the Else keyword is not preceded by a recognizable (correct) If statement, it generates an error ‘Else without If’. For every Else, there must be an If statement. However, for every If, we do not necessarily need an else statement.

Example 1: Missing If Statement

In this example, we display an input box that takes the user’s input and stores it in x. Then we encounter an Else keyword, but there was no If statement prior to it. This indeed will cause a compiler error: Else Without If.

Sub Else_Without_If()
x = InputBox("Set x value")'
'if statement should go here, but it’s missing. This will cause a compile error: Else without If
     MsgBox = "x value is equal to 1"
Else
     MsgBox = "x value is not equal to 1"
End If
End Sub

To solve this problem, we just need to add an If statement. An If statement consists of If [condition] Then.

Sub Else_Without_If()
x = InputBox("Set x value")
If x = 1 Then
     MsgBox = "x value is equal to 1"
Else
     MsgBox = "x value is not equal to 1"
End If
End Sub

correct input popup

x value is equal to 1 popup

Following good indentation practices is crucial for recognizing whether each if-else-then logic consists of the necessary  keywords (If statement, Else keyword, End If keyword).

If [condition] Then

[action]

Else

If [condition] Then

[action]

Else

[action]

End If

[action]

End If

Example 2: Else statement is inside a loop and If statement is outside

You might be surprised that you are getting the error when you already have the If statement present in the code and placed prior to the Else keyword and written correctly. The problem might not be apparent at first glance. But if we look closer, we will see that the scope of the If statement is different from that of the else statement.

Everything between the If statement and the End If keyword belongs to the scope of this If statement. Other scopes can also exist in the code due to the existence of loops such as For Next loop, Do Until loop or For Each Next loop.

A scope exists when a logical statement requires multiple keywords to indicate the start and end points of the statement. A problem occurs if you overlap scopes in a way that causes one to be partially placed inside the other. The correct way to have multiple scopes work with each other is to have one totally placed inside the other.

In the following example, If [condition] Then is followed by the beginning of a For loop followed by the Else keyword. This separates the If statement and the Else keyword and causes the error to show up.

Sub Else_Without_If()
x = InputBox("Set x value")
'starting the if statement scope
If x = 1 Then
     MsgBox "x value is equal to 1"
     ‘starting a new scope (For Next loop)
     For R = 1 To 5
'Else keyword is separated from its If statement because it’s in a different scope.
Else
     Next R
     MsgBox "x value is not equal to 1"
End If
End Sub

else without if on example

To fix the issue, we ensure that the If logical statement as a whole is fully encompassed within the For loop. Or the For loop is fully encompassed within the If logical statement Action; between If and Else or between Else and End If.

As a general rule, if a section of your code has a some status due to having a starting and ending point (If – Else, Else – End  If, For – Next, Do – Until) then you cannot start another section (scope) within it without ending it within the first section.

Start Point (If, Else, For, Do)

Another Start Point

Do Something

Another End Point

End Point (Else, End If, Next, Until)

To apply this to our example, we change it to the following code;

Sub Else_Without_If()
x = InputBox("Set x value")
'starting the if statement scope
If x = 1 Then
     MsgBox "x value is equal to 1"
     'starting a new scope (For Next loop)
     For R = 1 To 5
          MsgBox "x value is equal to 1"
     'ending the new scope within the same scope it was started in
     Next R
Else
     MsgBox "x value is not equal to 1"
End If
End Sub

Incorrect If Statement

Example 3: Placing the action on the same line with If Statement

Another very common mistake that is often made is to write the If statement in a way that is not compatible with utilizing the Else keyword.

If we want to use the Else keyword, we must place the action part of the If-Then-Else logic in the next line after the if statement. If we are not using the Else keyword, then we can place the action on the same line as the If statement and we do not write the Else keyword or the End If keyword.

When the action (that should be carried out if the condition is true) is placed on the same line as the If statement, then the If statement is considered complete. This is considered a shorthand way of writing the If – then logic.

That is why when compiler encounters an Else keyword after that, it does not find an If statement that belongs to the Else keyword, because that If statement has been completed with placing the action on the line as the If statement. The following code is NOT correct and will cause the compiler error: Else without If.

Sub Else_Without_If()
x = InputBox("Set x value")
If x = 1 Then MsgBox "x value is equal to 1"
Else
     MsgBox "x value is not equal to 1"
End If
End Sub

The action (MsgBox "x value is equal to 1") needs to be placed on the next row after the If statement in order to be able to have an Else statement used in the If-Then-Else logic. In the following code, we moved in the action statement to the next line, which fixes the problem.

Sub Else_Without_If()
x = InputBox("Set x value")
If x = 1 Then 
     MsgBox "x value is equal to 1"
Else
     MsgBox "x value is not equal to 1"
End If
End Sub

We now have covered all the possible causes of compile error: Else without if. To recap, if you get this error, check whether

1) There is an If statement in place that precedes the Else keyword.

2) The if statement line does not contain anything other than If [condition] Then.

3) Verify that the If statement and the Else keyword are not separated by another scope or section, such as loops.

See also: How to Fix the “End If without block If” Error

ImyaMo

0 / 0 / 0

Регистрация: 13.09.2019

Сообщений: 24

1

13.09.2019, 04:07. Показов 3683. Ответов 7

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

нужно написать макрос в Excel для подсчета количества пенсионеров определенного возраста и подсчета сколько из них женщин, и сколько мужчин (за пенсионеров считать женщин старше 60 лет и мужчин старше 65 лет)
Хотела чтобы проходил по каждой строчке возраста, а затем проверял пол, но что-то пошло не по плану

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Public Sub individual_zadanie()
Dim k As Integer 'пенсионеры определенного возраста
Dim k1 As Integer 'мужчины
Dim k2 As Integer 'женщины
Dim a As Integer
Dim iCell As Range
k1 = 0
k2 = 0
k = 0
Set iCell = Columns(5).Find(What:="*", LookIn:=xlFormulas, SearchDirection:=xlPrevious)
If Not iCell Is Nothing Then
MsgBox "Количество людей в базе: " & iCell.Row, , ""
Else
MsgBox "Людей в базе нет", vbExclamation, ""
End If
a = CDbl(InputBox("Введите возраст: "))
For i = 1 To iCell.Row
If (iCell.Value = a And a >= 60 And Columns(4) = "ж") Then k2 = k2 + 1
ElseIf (iCell.Value = a And a >= 65 And Columns(4) = "м") Then k1 = k1 + 1
Else: MsgBox "Не пенсионер!"
End If
 
Next i
k = k1 + k2
MsgBox "Женщин:" & k2
MsgBox "Мужчин:" & k1
MsgBox "Всего пенсионеров этого возраста:" & k
End Sub



0



SoftIce

es geht mir gut

11265 / 4747 / 1183

Регистрация: 27.07.2011

Сообщений: 11,438

13.09.2019, 04:39

2

Цитата
Сообщение от ImyaMo
Посмотреть сообщение

Visual Basic
1
2
3
4
If (iCell.Value = a And a >= 60 And Columns(4) = "ж") Then k2 = k2 + 1
ElseIf (iCell.Value = a And a >= 65 And Columns(4) = "м") Then k1 = k1 + 1
Else: MsgBox "Не пенсионер!"
End If
Visual Basic
1
2
3
4
5
6
7
If (iCell.Value = a And a >= 60 And Columns(4) = "ж") Then 
    k2 = k2 + 1
ElseIf (iCell.Value = a And a >= 65 And Columns(4) = "м") Then 
    k1 = k1 + 1
Else
   MsgBox "Не пенсионер!"
End If

Но это не единственная ошибка.



0



0 / 0 / 0

Регистрация: 13.09.2019

Сообщений: 24

13.09.2019, 04:47

 [ТС]

3

то есть проблема в том, что я не нажала enter??

а где еще ошибки, просто я первый день с vba работаю



0



es geht mir gut

11265 / 4747 / 1183

Регистрация: 27.07.2011

Сообщений: 11,438

13.09.2019, 04:54

4

Цитата
Сообщение от ImyaMo
Посмотреть сообщение

то есть проблема в том, что я не нажала enter??

При чем тут Enter ? Посмотрите внимательно.

Цитата
Сообщение от ImyaMo
Посмотреть сообщение

а где еще ошибки,

Без файла — гадание на кофейной гуще.



0



6878 / 2810 / 534

Регистрация: 19.10.2012

Сообщений: 8,573

13.09.2019, 08:16

5

Если первый день — ещё не поздно разучиться всюду втуливать integer…
Заменяйте всюду на long, если это реальная рабочая задача. Ну а для преподов можно и так оставить, им вероятно так привычнее



0



0 / 0 / 0

Регистрация: 13.09.2019

Сообщений: 24

13.09.2019, 09:32

 [ТС]

6

SoftIce, а можно на электронную почту скинуть, а то сюда не хочет прикрепляться. А, и нужно прикрепить ж таблицу саму (поддерж.макросы)?



0



es geht mir gut

11265 / 4747 / 1183

Регистрация: 27.07.2011

Сообщений: 11,438

13.09.2019, 09:59

7

Цитата
Сообщение от ImyaMo
Посмотреть сообщение

на электронную почту скинуть, а то сюда не хочет прикрепляться

Можете прислать. Но лучше заархивируйте, и всё прикрепится.



0



SoftIce

es geht mir gut

11265 / 4747 / 1183

Регистрация: 27.07.2011

Сообщений: 11,438

13.09.2019, 16:37

8

ImyaMo,

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Public Sub individual_zadanie()
    Dim k As Long 'всего в базе
    Dim k1 As Long  'мужчины
    Dim k2 As Long   'женщины
    Dim a As Long, iCell As Range, firstResult As String
m:  a = Val(InputBox("Введите возраст: ", , 65))
    If a < 60 Then GoTo m
    With Worksheets(1).Columns(5)
         Set iCell = .Find("*", LookIn:=xlValues)
         If Not iCell Is Nothing Then
             firstResult = iCell.Address
             Do
                k = k + 1
                If (iCell.Value = a) And (a >= 60) And (Cells(iCell.Row, 4) = "ж") Then
                   k2 = k2 + 1
                ElseIf (iCell.Value = a) And (a >= 65) And (Cells(iCell.Row, 4) = "м") Then
                   k1 = k1 + 1
                End If
                Set iCell = .FindNext(iCell)
                If iCell Is Nothing Then Exit Do
             Loop While iCell.Address <> firstResult
         End If
    End With
    If k > 0 Then If (k1 = 0 And k2 = 0) Then MsgBox "Пенсионеров " & a & "-летнего возраста в базе нет": Exit Sub
    MsgBox IIf(k = 0, "Людей в базе нет", "Количество людей в базе: " & k & vbCrLf & "Всего пенсионеров " & a & "-летнего возраста: " & k1 + k2 & vbCrLf & "Из них:" & vbCrLf & "Женщин: " & k2 & vbCrLf & "Мужчин: " & k1)
End Sub



0



I don’t have much experience at all with VBA, and am trying to write a backend function to tally up certain fields depending on the value of another field. I have a bunch of nested If Then and ElseIf Then statements, and am getting the error on my first ElseIf. Here’s the block in question:

ElseIf rCell.Value = "Blueprint" Then
    aCell = Range("DR")
    If aCell.Value = "Yes" Then
        aCell = Range("ER")
            If aCell.Value = "Yes" Then
              PHASEREVIEWCHECKER = True
             End If
            ElseIf aCell.Value = "No" Or aCell.Value = "N/A" Or aCell.Value = "Unknown" Then
                PHASEREVIEWCHECKER = False
         End If
    ElseIf aCell.Value = "No" Or aCell.Value = "N/A" Or aCell.Value = "Unknown" Then
        PHASEREVIEWCHECKER = False
    End If

Most of the solutions I’ve found to this problem involve indenting after every Then or making sure there’s enough End Ifs, but I’ve done that and the problem persists. Any help would be greatly appreciated.

Edit 2: Problem has been solved, just tinkered with End Ifs until it worked. Thanks all for the help!

asked Aug 7, 2017 at 18:04

JPezzulla's user avatar

3

Each ElseIf does not get its own End If

Also proper indentation helps find these problems.

The proper method is:

IF ... Then
    'do somthing
ElseIf
    'do somthing
Else
    'do somthing
End If

With the ElseIf and Else being optional.

ElseIf rCell.Value = "Blueprint" Then
    aCell = Range("DR")
    If aCell.Value = "Yes" Then
        aCell = Range("ER")
        If aCell.Value = "Yes" Then
            PHASEREVIEWCHECKER = True
        ElseIf aCell.Value = "No" Or aCell.Value = "N/A" Or aCell.Value = "Unknown" Then
            PHASEREVIEWCHECKER = False
        End If
    ElseIf aCell.Value = "No" Or aCell.Value = "N/A" Or aCell.Value = "Unknown" Then
        PHASEREVIEWCHECKER = False
    End If
End If

Here is your long nested ifs, simplified with Ands

Public Function PHASEREVIEWCHECKER(R As Integer)
Dim rCell As Range

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set rCell = Range("CR")
If rCell.Value = "Initiate" Then
    If Range("DR").Value = "Yes" Then
        PHASEREVIEWCHECKER = True
    Else
        PHASEREVIEWCHECKER = False
    End If
ElseIf rCell.Value = "Blueprint" Then
    If Range("DR").Value = "Yes" And Range("ER") = "Yes" Then
        PHASEREVIEWCHECKER = True
    Else
        PHASEREVIEWCHECKER = False
    End If
ElseIf rCell.Value = "Design" Then
    If Range("DR").Value = "Yes" And Range("ER").Value = "Yes" And Range("FR").Value = "Yes" Then
        PHASEREVIEWCHECKER = True
    Else
        PHASEREVIEWCHECKER = False
    End If
ElseIf rCell.Value = "Build" Then
    If Range("DR").Value = "Yes" And Range("ER").Value = "Yes" And Range("FR").Value = "Yes" And Range("GR").Value = "Yes" Then
        PHASEREVIEWCHECKER = True
    Else
        PHASEREVIEWCHECKER = False
    End If
ElseIf rCell.Value = "Test & Train" Then
    If Range("DR").Value = "Yes" And Range("ER").Value = "Yes" And Range("FR").Value = "Yes" And Range("GR").Value = "Yes" _
        And Range("HR").Value = "Yes" Then
        PHASEREVIEWCHECKER = True
    Else
        PHASEREVIEWCHECKER = False
    End If
ElseIf rCell.Value = "Deploy & Operate" Then
    If Range("DR").Value = "Yes" And Range("ER").Value = "Yes" And Range("FR").Value = "Yes" And Range("GR").Value = "Yes" _
        And Range("HR").Value = "Yes" And Range("IR").Value = "Yes" Then
        PHASEREVIEWCHECKER = True
    Else
        PHASEREVIEWCHECKER = False
    End If
End If
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Function

answered Aug 7, 2017 at 18:08

Scott Craner's user avatar

Scott CranerScott Craner

147k9 gold badges48 silver badges80 bronze badges

2

Понравилась статья? Поделить с друзьями:
  • Ошибка в unturned the server is running
  • Ошибка в автоматической коробке передач
  • Ошибка в unturned different version
  • Ошибка в автомате ауди а6
  • Ошибка в unity the associated script