Ошибка vba else without if else

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

Здравствуйте. Наверное, напутала что-то с типами данных.. При выполнении данного макроса возникает ошибка «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  

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

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.

Contents

  • Missing If Statement
    • Example 1: Missing If Statement
    • Example 2: Else statement is inside a loop and If statement is outside
  • Incorrect If Statement
    • Example 3: Placing the action on the same line with If Statement

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

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» :  

  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  

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

ImyaMo

0 / 0 / 0

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

Сообщений: 24

1

13.09.2019, 04:07. Показов 3168. Ответов 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

11264 / 4746 / 1183

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

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

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

11264 / 4746 / 1183

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

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

13.09.2019, 04:54

4

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

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

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

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

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

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

0

6874 / 2806 / 533

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

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

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

11264 / 4746 / 1183

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

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

13.09.2019, 09:59

7

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

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

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

0

SoftIce

es geht mir gut

11264 / 4746 / 1183

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

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

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 am hoping someone can help me with the following code. I keep getting the ‘Else Without If’ control error and I don’t understand why?

If Sheets("Travel Expense Voucher").Range("D5") = 2 And Sheets("Travel Expense Voucher").Range("Meals") <> "" Then Sheets("Expense Code Processing").Range("C2") = "62495"
    ElseIf Sheets("Travel Expense Voucher").Range("D5") = 1 And Sheets("Travel Expense Voucher").Range("Meals") <> "" And cmbOVNRTN = ("Return") And cmbInOutState = ("In-State") Then Sheets("Expense Code Processing").Range("C2") = "62407"
    ElseIf Sheets("Travel Expense Voucher").Range("D5") = 1 And Sheets("Travel Expense Voucher").Range("Meals") <> "" And cmbOVNRTN = ("Overnight") And cmbInOutState = ("In-State") Then Sheets("Expense Code Processing").Range("C2") = "62410"
    ElseIf Sheets("Travel Expense Voucher").Range("D5") = 1 And Sheets("Travel Expense Voucher").Range("Meals") <> "" And cmbOVNRTN = ("Return") And cmbInOutState = ("Out-of-State") Then Sheets("Expense Code Processing").Range("C2") = "62430"
    ElseIf Sheets("Travel Expense Voucher").Range("D5") = 1 And Sheets("Travel Expense Voucher").Range("Meals") <> "" And cmbOVNRTN = ("Overnight") And cmbInOutState = ("Out-of-State") Then Sheets("Expense Code Processing").Range("C2") = "62417"
End If

asked May 3, 2020 at 17:45

Kristen's user avatar

3

Indentation is needed for the If statement.

Also, you can use variables and a With statement to make it more clear. I also added a Boolean to make the ElseIf a little shorter:

Sub t()
Dim ws As Worksheet, destWS As Worksheet
Set ws = Sheets("Travel Expense Voucher")
Set destWS = Sheets("Expense Code Processing")
Dim oneMeal As Boolean
oneMeal = False
With ws
    If .Range("D5") = 1 And .Range("Meals") <> "" Then oneMeal = True
    If .Range("D5") = 2 And .Range("Meals") <> "" Then
        destWS.Range("C2") = "62495"
    ElseIf oneMeal And cmbOVNRTN = ("Return") And cmbInOutState = ("In-State") Then destWS.Range("C2") = "62407"
    ElseIf oneMeal And cmbOVNRTN = ("Overnight") And cmbInOutState = ("In-State") Then destWS.Range("C2") = "62410"
    ElseIf oneMeal And cmbOVNRTN = ("Return") And cmbInOutState = ("Out-of-State") Then destWS.Range("C2") = "62430"
    ElseIf oneMeal And cmbOVNRTN = ("Overnight") And cmbInOutState = ("Out-of-State") Then destWS.Range("C2") = "62417"
    End If
End With
End Sub

answered May 3, 2020 at 17:57

BruceWayne's user avatar

BruceWayneBruceWayne

22.8k14 gold badges62 silver badges109 bronze badges

3

I am hoping someone can help me with the following code. I keep getting the ‘Else Without If’ control error and I don’t understand why?

If Sheets("Travel Expense Voucher").Range("D5") = 2 And Sheets("Travel Expense Voucher").Range("Meals") <> "" Then Sheets("Expense Code Processing").Range("C2") = "62495"
    ElseIf Sheets("Travel Expense Voucher").Range("D5") = 1 And Sheets("Travel Expense Voucher").Range("Meals") <> "" And cmbOVNRTN = ("Return") And cmbInOutState = ("In-State") Then Sheets("Expense Code Processing").Range("C2") = "62407"
    ElseIf Sheets("Travel Expense Voucher").Range("D5") = 1 And Sheets("Travel Expense Voucher").Range("Meals") <> "" And cmbOVNRTN = ("Overnight") And cmbInOutState = ("In-State") Then Sheets("Expense Code Processing").Range("C2") = "62410"
    ElseIf Sheets("Travel Expense Voucher").Range("D5") = 1 And Sheets("Travel Expense Voucher").Range("Meals") <> "" And cmbOVNRTN = ("Return") And cmbInOutState = ("Out-of-State") Then Sheets("Expense Code Processing").Range("C2") = "62430"
    ElseIf Sheets("Travel Expense Voucher").Range("D5") = 1 And Sheets("Travel Expense Voucher").Range("Meals") <> "" And cmbOVNRTN = ("Overnight") And cmbInOutState = ("Out-of-State") Then Sheets("Expense Code Processing").Range("C2") = "62417"
End If

asked May 3, 2020 at 17:45

Kristen's user avatar

3

Indentation is needed for the If statement.

Also, you can use variables and a With statement to make it more clear. I also added a Boolean to make the ElseIf a little shorter:

Sub t()
Dim ws As Worksheet, destWS As Worksheet
Set ws = Sheets("Travel Expense Voucher")
Set destWS = Sheets("Expense Code Processing")
Dim oneMeal As Boolean
oneMeal = False
With ws
    If .Range("D5") = 1 And .Range("Meals") <> "" Then oneMeal = True
    If .Range("D5") = 2 And .Range("Meals") <> "" Then
        destWS.Range("C2") = "62495"
    ElseIf oneMeal And cmbOVNRTN = ("Return") And cmbInOutState = ("In-State") Then destWS.Range("C2") = "62407"
    ElseIf oneMeal And cmbOVNRTN = ("Overnight") And cmbInOutState = ("In-State") Then destWS.Range("C2") = "62410"
    ElseIf oneMeal And cmbOVNRTN = ("Return") And cmbInOutState = ("Out-of-State") Then destWS.Range("C2") = "62430"
    ElseIf oneMeal And cmbOVNRTN = ("Overnight") And cmbInOutState = ("Out-of-State") Then destWS.Range("C2") = "62417"
    End If
End With
End Sub

answered May 3, 2020 at 17:57

BruceWayne's user avatar

BruceWayneBruceWayne

22.8k14 gold badges62 silver badges109 bronze badges

3

  • #1

Hi guys,

I’m new at writing vba and am trying to get this user form working but keep getting the compile error: Else without if.

Code:

Private Sub cmdOK_Click()
    ActiveWorkbook.Sheets("Course Bookings").ActivateRange("A1").Select
    Do
    If IsEmpty(ActiveCell) = False Then
        ActiveCell.Offset(1, 0).Select
    End If
    Loop Until IsEmpty(ActiveCell) = True
    ActiveCell.Value = txtName.Value
    ActiveCell.Offset(0, 1) = txtPhone.Value
    ActiveCell.Offset(0, 2) = cboDepartment.Value
    ActiveCell.Offset(0, 3) = cboCourse.Value
    If optIntroduction = True Then ActiveCell.Offset(0, 4).Value = "Intro"
    [B]ElseIf optIntermediate = True Then[/B]
            ActiveCell.Offset(0, 4).Value = "Intermd"
                Else
                ActiveCell.Offset(0, 4).Value = "Adv"
                End If
                If chkLunch = True Then
                    ActiveCell.Offset(0, 5).Value = "Yes"
                Else
                    ActiveCell.Offset(0, 5).Value = "No"
                End If
                If chkVegetarian = True Then
                ActiveCell.Offset(0, 6).Value = "Yes"
                Else
                    If chkLunch = False Then
                    ActiveCell.Offset(0, 6).Value = ""
                    Else
                    ActiveCell.Offset(0, 6).Value = "No"
                End If
                Range("A1").Select

The bolded text is what the editor highlights. What am I going wrong?

Last used cell?

Press Ctrl+End to move to what Excel thinks is the last used cell.

  • #2

This a complete If statement.

Code:

If optIntroduction = True Then ActiveCell.Offset(0, 4).Value = "Intro"

Anything after it isn’t part of the If statement.

Try this.

Code:

If optIntroduction = True Then 
       ActiveCell.Offset(0, 4).Value = "Intro"
ElseIf  optIntermediate = True Then
       ActiveCell.Offset(0, 4).Value = "Intermd"
Else
       ActiveCell.Offset(0, 4).Value = "Adv"
End If

  • #3

Thanks Norie!

However, now I’m getting a different error: Block If without End If. The new code I’m trying is…

Code:

Private Sub cmdOK_Click()
    ActiveWorkbook.Sheets("Course Bookings").ActivateRange("A1").Select
Do
If IsEmpty(ActiveCell) = False Then
    ActiveCell.Offset(1, 0).Select
End If
Loop Until IsEmpty(ActiveCell) = True
    ActiveCell.Value = txtName.Value
    ActiveCell.Offset(0, 1) = txtPhone.Value
    ActiveCell.Offset(0, 2) = cboDepartment.Value
    ActiveCell.Offset(0, 3) = cboCourse.Value
If optIntroduction = True Then
       ActiveCell.Offset(0, 4).Value = "Intro"
ElseIf optIntermediate = True Then
       ActiveCell.Offset(0, 4).Value = "Intermd"
Else
       ActiveCell.Offset(0, 4).Value = "Adv"
End If
    If chkLunch = True Then
        ActiveCell.Offset(0, 5).Value = "Yes"
    Else
        ActiveCell.Offset(0, 5).Value = "No"
    End If
    If chkVegetarian = True Then
        ActiveCell.Offset(0, 6).Value = "Yes"
    Else
    If chkLunch = False Then
        ActiveCell.Offset(0, 6).Value = ""
    Else
        ActiveCell.Offset(0, 6).Value = "No"
    End If
        Range("A1").Select
[B]End Sub[/B]

It now highlights «End Sub.»

Sorry completely new at vba trying to debug code I got from someone.

  • #4

Proper indentation of code will help discover these issues.
You were missing the Red End If

Rich (BB code):

Private Sub cmdOK_Click()
ActiveWorkbook.Sheets("Course Bookings").ActivateRange("A1").Select
Do
    If IsEmpty(ActiveCell) = False Then
        ActiveCell.Offset(1, 0).Select
    End If
Loop Until IsEmpty(ActiveCell) = True
 
ActiveCell.Value = txtName.Value
ActiveCell.Offset(0, 1) = txtPhone.Value
ActiveCell.Offset(0, 2) = cboDepartment.Value
ActiveCell.Offset(0, 3) = cboCourse.Value
 
If optIntroduction = True Then
    ActiveCell.Offset(0, 4).Value = "Intro"
ElseIf optIntermediate = True Then
    ActiveCell.Offset(0, 4).Value = "Intermd"
Else
    ActiveCell.Offset(0, 4).Value = "Adv"
End If
 
If chkLunch = True Then
    ActiveCell.Offset(0, 5).Value = "Yes"
Else
    ActiveCell.Offset(0, 5).Value = "No"
End If
 
If chkVegetarian = True Then
    ActiveCell.Offset(0, 6).Value = "Yes"
Else
    If chkLunch = False Then
        ActiveCell.Offset(0, 6).Value = ""
    Else
        ActiveCell.Offset(0, 6).Value = "No"
    End If
End If
Range("A1").Select
End Sub

  • #5

Thanks Jonmo1,

No longer coming up with that error.. But now it is coming with ‘Runtime erorr 9 subscript out of range’

  • #6

Where is that error happening?

  • #7

Don’t worry, fixed it!

I changed

Code:

ActiveWorkbook.Sheets("Course Bookings").ActivateRange("A1").Select

to..

Code:

    Application.Goto (ActiveWorkbook.Sheets("Course Bookings").Range("A1"))

The whole code is now..

Code:

Private Sub cmdOK_Click()
    'ActiveWorkbook.Sheets("Course Bookings").ActivateRange("A1").Select
    Application.Goto (ActiveWorkbook.Sheets("Course Bookings").Range("A1"))
Do
If IsEmpty(ActiveCell) = False Then
    ActiveCell.Offset(1, 0).Select
End If
Loop Until IsEmpty(ActiveCell) = True
    ActiveCell.Value = txtName.Value
    ActiveCell.Offset(0, 1) = txtPhone.Value
    ActiveCell.Offset(0, 2) = cboDepartment.Value
    ActiveCell.Offset(0, 3) = cboCourse.Value
If optIntroduction = True Then
       ActiveCell.Offset(0, 4).Value = "Intro"
ElseIf optIntermediate = True Then
       ActiveCell.Offset(0, 4).Value = "Intermd"
Else
       ActiveCell.Offset(0, 4).Value = "Adv"
End If
    If chkLunch = True Then
        ActiveCell.Offset(0, 5).Value = "Yes"
    Else
        ActiveCell.Offset(0, 5).Value = "No"
    End If
    If chkVegetarian = True Then
        ActiveCell.Offset(0, 6).Value = "Yes"
    Else
    If chkLunch = False Then
        ActiveCell.Offset(0, 6).Value = ""
    Else
        ActiveCell.Offset(0, 6).Value = "No"
    End If
        Range("A1").Select
    End If
End Sub

Cheers for your help

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Private Sub Command1_Click()
Dim day, month, year, sum, ost, tmp As Integer
day = Text1.Text
month = Text2.Text
year = Text3.Text
Call myChoose(month, sum, year)
sum = sum - day
If (month = 12) Then
    month = 1
    year = year + 1
Else
    month = month + 1
End If
point:
tmp = 0
Call myChoose(month, tmp, year)
If ((sum + tmp) < 5000) Then
    Call myChoose(month, sum, year)
    If (month = 12) Then
        month = 1
        year = year + 1
    Else
        month = month + 1
    End If
    GoTo point
End If
ost = 5000 - sum
If (ost = 0) Then
    If (month = 1) Then
        month = 12
        year = year - 1
    Else
        month = month - 1
    End If
    Call myChoose(month, ost, year)
End If
Text4.Text = ost
Text5.Text = month
Text6.Text = year
 
End Sub
 
Sub myChoose(month, sum, year)
Select Case month
    Case 1, 3, 5, 7, 8, 10, 12
        sum = sum + 31
    Case 2
        If (year Mod 4 = 0) Then
            sum = sum + 29
        Else
            sum = sum + 28
        End If
    Case 4, 6, 9, 11
        sum = sum + 30
    End Select
End Sub

  • Ошибка v0100 сузуки гранд витара
  • Ошибка vba 1004 при сохранении файла
  • Ошибка variable used without being declared
  • Ошибка utweb exe как убрать
  • Ошибка variable sized object may not be initialized