Vba excel for внутри if

Why does this code not work?? It throws compile error: Next without for

Because you have a next without a corresponding For. For/Next and For Each/Next must be paired, you can’t open a For loop without a Next and you can’t use Next without `For.

Simply:

if a = dumm then a = a + 1

This increments your a value within the loop. I’m unclear as to why you think this isn’t applicable, because whether you increment a and then run the code, or skip to the next a (which is functionally equivalent to incrementing it via +1), the result should be same

Or, you could add a label and a GoTo statement:

For a = 1 to 10
    if a = dumm then 
        GoTo MyLabel 
    end if
    'statements that need to run when the if statement is not true

MyLabel:
next a 

Or, and my preference, just use proper boolean expressions:

For a = 1 to 10
    if not a = dumm Then
        'statements that need to run when the if statement is not true
    end if
Next

If you don’t want to continue the loop at all, then either add an Exit statement,

For a = 1 to 10
    if a = dumm Then Exit For
    'statements that need to run when the if statement is not true

Next

or use a Do/While loop with proper escape conditions:

a = 1
Do 
    'statements go here...    
    a = a + 1
Loop While a <= 10 and Not a = dumm 

 

Andromed

Пользователь

Сообщений: 47
Регистрация: 01.01.1970

#1

15.07.2013 11:57:29

Всем доброго!
Подскажите, пожалуйста, как правильно If…Then вложить в For…Next в следующем коде:

Код
Sub bbb()
Dim x, i
   x = 3

   For i = 1 to 10
      If i = x Then
         [COLOR=#ff0000][B]' ЗДЕСЬ НУЖНО СРАЗУ ПЕРЕЙТИ К СЛЕДУЮЩЕМУ i[/B][/COLOR]
      End If

      ' <ПРОДОЛЖЕНИЕ КОДА>

   Next i

End Sub

Если просто написать «Next i», то пишет, что Next без For.
Понимаю, что вопрос элементарный, но ответ найти не могу

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#2

15.07.2013 12:00:10

Цитата
Andromed пишет:
 ЗДЕСЬ НУЖНО СРАЗУ ПЕРЕЙТИ К СЛЕДУЮЩЕМУ i  

Так «следующий» i и будет на очередной итерации цикла. Уточните вопрос.

 

Pelena

Пользователь

Сообщений: 1416
Регистрация: 22.12.2012

#3

15.07.2013 12:02:08

Может так

Код
Sub bbb() 
Dim x, i 
x = 3 

For i = 1 to 10 

If i <> x Then 
' <ПРОДОЛЖЕНИЕ КОДА> 
End If 

Next i 

End Sub 
 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

#4

15.07.2013 12:04:38

Так?

Код
    For i = 1 To 10
        If i <> x Then
            ' <ПРОДОЛЖЕНИЕ КОДА>
        End If
    Next i
 

Andromed

Пользователь

Сообщений: 47
Регистрация: 01.01.1970

Hugo, Pelena, смысл именно такой, спасибо! Но хочется пойти от обратного и сделать код более читаемым. Можно ли при выполнении условия перейти сразу к следующей итерации цикла из блока If…Then, чтобы <ПРОДОЛЖЕНИЕ КОДА> не выполнялось? Если да, то как это правильно оформить?

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Может быть метку поставить?

 

Andromed

Пользователь

Сообщений: 47
Регистрация: 01.01.1970

не хотел, но наверное придется. спасибо!

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

#8

15.07.2013 12:59:09

Ох уж…

Код
For i = 1 to 10 
If i = x Then 
else
' <ПРОДОЛЖЕНИЕ КОДА>  
End If 
Next i

Я сам — дурнее всякого примера! …

Цикл For… Next в VBA Excel, его синтаксис и описание отдельных компонентов. Примеры использования цикла For… Next.

Цикл For… Next в VBA Excel предназначен для выполнения группы операторов необходимое количество раз, заданное управляющей переменной цикла — счетчиком. При выполнении цикла значение счетчика после каждой итерации увеличивается или уменьшается на число, указанное выражением оператора Step, или, по умолчанию, на единицу. Когда необходимо применить цикл к элементам, количество которых и индексация в группе (диапазон, массив, коллекция) неизвестны, следует использовать цикл For Each… Next.


For counter = start To end [ Step step ]

    [ statements ]

    [ Exit For ]

    [ statements ]

Next [ counter ]


For счетчик = начало To конец [ Step шаг ]

    [ операторы ]

    [ Exit For ]

    [ операторы ]

Next [ счетчик ]


В квадратных скобках указаны необязательные атрибуты цикла For… Next.

Компоненты цикла For… Next

Компонент Описание
counter Обязательный атрибут. Числовая переменная, выполняющая роль счетчика, которую еще называют управляющей переменной цикла.
start Обязательный атрибут. Числовое выражение, задающее начальное значение счетчика.
end Обязательный атрибут. Числовое выражение, задающее конечное значение счетчика.
Step* Необязательный атрибут. Оператор, указывающий, что будет задан шаг цикла.
step Необязательный атрибут. Числовое выражение, задающее шаг цикла. Может быть как положительным, так и отрицательным.
statements Необязательный** атрибут. Операторы вашего кода.
Exit For Необязательный атрибут. Оператор выхода из цикла до его окончания.
Next [ counter ] Здесь counter — необязательный атрибут. Это то же самое имя управляющей переменной цикла, которое можно здесь не указывать.

*Если атрибут Step отсутствует, цикл For… Next выполняется с шагом по умолчанию, равному 1.

**Если не использовать в цикле свой код, смысл применения цикла теряется.

Примеры циклов For… Next

Вы можете скопировать примеры циклов в свой модуль VBA, последовательно запускать их на выполнение и смотреть результаты.

Простейший цикл

Заполняем десять первых ячеек первого столбца активного листа Excel цифрами от 1 до 10:

Sub test1()

Dim i As Long

  For i = 1 To 10

    Cells(i, 1) = i

  Next

End Sub

Простейший цикл с шагом

В предыдущий цикл добавлен оператор Step со значением 3, а результаты записываем во второй столбец:

Sub test2()

Dim i As Long

  For i = 1 To 10 Step 3

    Cells(i, 2) = i

  Next

End Sub

Цикл с отрицательными аргументами

Этот цикл заполняет десять первых ячеек третьего столбца в обратной последовательности:

Sub test3()

Dim i As Long

  For i = 0 To 9 Step 1

    Cells(i + 10, 3) = i + 10

  Next

End Sub

Увеличиваем размер шага до -3 и записываем результаты в четвертый столбец активного листа Excel:

Sub test4()

Dim i As Long

  For i = 0 To 9 Step 3

    Cells(i + 10, 4) = i + 10

  Next

End Sub

Вложенный цикл

Внешний цикл последовательно задает индексы первых десяти строк активного листа, а вложенный цикл складывает числа в первых четырех ячейках строки с текущем индексом и записывает сумму в ячейку пятого столбца. Перед запуском вложенного цикла с накопительным сложением, пятую ячейку соответствующей строки обнуляем, чтобы в случае нахождения в ней какого-либо числа, оно не прибавилось к итоговой сумме.

Sub test5()

Dim i1 As Long, i2 As Long

  For i1 = 1 To 10

‘Пятой ячейке в строке i1 присваиваем 0

    Cells(i1, 5) = 0

      For i2 = 1 To 4

        Cells(i1, 5) = Cells(i1, 5) + Cells(i1, i2)

      Next

  Next

End Sub

Выход из цикла

В шестой столбец активного листа запишем названия десяти животных, конечно же, с помощью цикла For… Next:

Sub test6()

Dim i As Long

  For i = 1 To 10

    Cells(i, 6) = Choose(i, «Медведь», «Слон», «Жираф», «Антилопа», _

    «Крокодил», «Зебра», «Тигр», «Ящерица», «Лев», «Бегемот»)

  Next

End Sub

Следующий цикл будет искать в шестом столбце крокодила, который съел галоши. В ячейку седьмого столбца цикл, пока не встретит крокодила, будет записывать строку «Здесь был цикл», а когда обнаружит крокодила, запишет «Он съел галоши» и прекратит работу, выполнив команду Exit For. Это будет видно по ячейкам рядом с названиями животных ниже крокодила, в которых не будет текста «Здесь был цикл».

Sub test7()

Dim i As Long

  For i = 1 To 10

    If Cells(i, 6) = «Крокодил» Then

      Cells(i, 7) = «Он съел галоши»

      Exit For

        Else

      Cells(i, 7) = «Здесь был цикл»

    End If

  Next

End Sub


Результат работы циклов For… Next из примеров:

Результат работы циклов For... Next из примеров

Результат работы циклов For… Next

Такие данные на активном листе Excel вы получите, если последовательно запустите на выполнение в редакторе VBA все семь подпрограмм из примеров, демонстрирующих работу циклов For… Next.

Цикл с дробными аргументами

Атрибуты start, end и step могут быть представлены числом, переменной или числовым выражением:

For i = 1 To 20 Step 2

For i = a To b Step c

For i = a 3 To 2b + 1 Step c/2  

В результате вычисления значения переменной вне цикла или выражения внутри его может получиться дробный результат. VBA Excel округлит его до целого числа, используя бухгалтерское округление:

‘Значения атрибутов до округления

For i = 1.5 To 10.5 Step 2.51

‘Округленные значения атрибутов

For i = 2 To 10 Step 3  

Старайтесь не допускать попадания в тело цикла For… Next неокругленных значений аргументов, чтобы не получить непредсказуемые результаты его выполнения. Если без дробных чисел не обойтись, а необходимо использовать обычное округление, применяйте в коде VBA функцию рабочего листа WorksheetFunction.Round для округления числа перед использованием его в цикле For… Next.


In this Article

  • VBA Loop Quick Examples
    • For Each Loops
    • For Next Loops
    • Do While Loops
    • Do Until Loops
  • VBA Loop Builder
  • VBA For Next Loop
    • For Loop Syntax
    • For Loop Step
    • For Loop Step – Inverse
    • Nested For Loop
    • Exit For
    • Continue For
  • VBA For Each Loop
    • For Each Cell in Range
    • For Each Worksheet in Workbook
    • For Each Open Workbook
    • For Each Shape in Worksheet
    • For Each Shape in Each Worksheet in Workbook
    • For Each – IF Loop
  • VBA Do While Loop
    • Do While
    • Loop While
  • VBA Do Until Loop
    • Do Until
    • Loop Until
  • Exit Do Loop
  • End or Break Loop
  • More Loop Examples
    • Loop Through Rows
    • Loop Through Columns
    • Loop Through Files in a Folder
    • Loop Through Array
  • Loops in Access VBA

To work effectively in VBA, you must understand Loops.

Loops allow you to repeat a code block a set number of times or repeat a code block on a each object in a set of objects.

First we will show you a few examples to show you what loops are capable of. Then we will teach you everything about loops.

VBA Loop Quick Examples

For Each Loops

For Each Loops loop through every object in a collection, such as every worksheet in workbook or every cell in a range.

Loop Through all Worksheets in Workbook

This code will loop through all worksheets in the workbook, unhiding each sheet:

Sub LoopThroughSheets()
Dim ws As Worksheet
 
    For Each ws In Worksheets
        ws.Visible = True
    Next
 
End Sub

Loop Through All Cells in Range

This code will loop through a range of cells, testing if the cell value is negative, positive, or zero:

Sub If_Loop()
Dim Cell as Range
 
  For Each Cell In Range("A2:A6")
    If Cell.Value > 0 Then
      Cell.Offset(0, 1).Value = "Positive"
    ElseIf Cell.Value < 0 Then
      Cell.Offset(0, 1).Value = "Negative"
    Else
      Cell.Offset(0, 1).Value = "Zero"
     End If
  Next Cell
 
End Sub

vba else if statement

For Next Loops

Another type of “For” Loop is the For Next Loop.  The For Next Loop allows you to loop through integers.

This code will loop through integers 1 through 10, displaying each with a message box:

Sub ForLoop()
    Dim i As Integer
    For i = 1 To 10
        MsgBox i
    Next i
End Sub

Do While Loops

Do While Loops will loop while a condition is met. This code will also loop through integers 1 through 10, displaying each with a message box.

Sub DoWhileLoop()
    Dim n As Integer
    n = 1
    Do While n < 11
        MsgBox n
        n = n + 1
    Loop
End Sub

Do Until Loops

Conversely, Do Until Loops will loop until a condition is met. This code does the same thing as the previous two examples.

Sub DoUntilLoop()
    Dim n As Integer
    n = 1
    Do Until n >= 10
        MsgBox n
        n = n + 1
    Loop
End Sub

We will discuss this below, but you need to be extremely careful when creating Do While or Do Until loops so that you don’t create a never ending loop.

VBA Loop Builder

vba loop builder

This is a screenshot of the “Loop Builder” from our Premium VBA Add-in: AutoMacro. The Loop Builder allows you to quickly and easily build loops to loop through different objects, or numbers. You can perform actions on each object and/or select only objects that meet certain criteria.

The add-in also contains many other code builders, an extensive VBA code library, and an assortment of coding tools. It’s a must have for any VBA developer.

Now we will cover the different types of loops in depth.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

VBA For Next Loop

For Loop Syntax

The For Next Loop allows you to repeat a block of code a specified number of times. The syntax is:

[Dim Counter as Integer]

For Counter = Start to End [Step Value]
    [Do Something]
Next [Counter]

Where the items in brackets are optional.

  • [Dim Counter as Long] – Declares the counter variable. Required if Option Explicit is declared at the top of your module.
  • Counter – An integer variable used to count
  • Start – The start value (Ex. 1)
  • End – The end value (Ex. 10)
  • [Step Value] – Allows you to count every n integers instead of every 1 integer. You can also go in reverse with a negative value (ex. Step -1)
  • [Do Something] – The code that will repeat
  • Next [Counter] – Closing statement to the For Next Loop. You can include the Counter or not. However, I strongly recommend including the counter as it makes your code easier to read.

If that’s confusing, don’t worry. We will review some examples:

Count to 10

This code will count to 10 using a For-Next Loop:

Sub ForEach_CountTo10()

Dim n As Integer
For n = 1 To 10
    MsgBox n
Next n

End Sub

For Loop Step

Count to 10 – Only Even Numbers

This code will count to 10 only counting even numbers:

Sub ForEach_CountTo10_Even()

Dim n As Integer
For n = 2 To 10 Step 2
    MsgBox n
Next n

End Sub

Notice we added “Step 2”. This tells the For Loop to “step” through the counter by 2.  We can also use a negative step value to step in reverse:

VBA Programming | Code Generator does work for you!

For Loop Step – Inverse

Countdown from 10

This code will countdown from 10:

Sub ForEach_Countdown_Inverse()

Dim n As Integer
For n = 10 To 1 Step -1
    MsgBox n
Next n
MsgBox "Lift Off"

End Sub

Delete Rows if Cell is Blank

I’ve most frequently used a negative step For-Loop to loop through ranges of cells, deleting rows that meet certain criteria.  If you loop from the top rows to the bottom rows, as you delete rows you will mess up your counter.

This example will delete rows with blank cells (starting from the bottom row):

Sub ForEach_DeleteRows_BlankCells()

Dim n As Integer
For n = 10 To 1 Step -1
    If Range("a" & n).Value = "" Then
        Range("a" & n).EntireRow.Delete
    End If
Next n

End Sub

Nested For Loop

You can “nest” one For Loop inside another For Loop. We will use Nested For Loops to create a multiplication table:

Sub Nested_ForEach_MultiplicationTable()

Dim row As Integer, col As Integer

For row = 1 To 9
    For col = 1 To 9
        Cells(row + 1, col + 1).Value = row * col
    Next col
Next row

End Sub

vba nested for loop

Exit For

The Exit For statement allows you to exit a For Next loop immediately.

You would usually use Exit For along with an If Statement, exiting the For Next Loop if a certain condition is met.

For example, you might use a For Loop to find a cell. Once that cell is found, you can exit the loop to speed up your code.

This code will loop through rows 1 to 1000, looking for “error” in column A. If it’s found, the code will select the cell, alert you to the found error, and exit the loop:

Sub ExitFor_Loop()

Dim i As Integer
 
For i = 1 To 1000
    If Range("A" & i).Value = "error" Then
        Range("A" & i).Select
        MsgBox "Error Found"
        Exit For
    End If
Next i

End Sub

Important: In the case of Nested For Loops, Exit For only exits the current For Loop, not all active Loops.

Continue For

VBA does not have the “Continue” command that’s found in Visual Basic. Instead, you will need to use “Exit”.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA For Each Loop

The VBA For Each Loop will loop through all objects in a collection:

  • All cells in a range
  • All worksheets in a workbook
  • All shapes in a worksheet
  • All open workbooks

You can also use Nested For Each Loops to:

  • All cells in a range on all worksheets
  • All shapes on all worksheets
  • All sheets in all open workbooks
  • and so on…

The syntax is:

For Each Object in Collection
[Do Something]
Next [Object]

Where:

  • Object – Variable representing a Range, Worksheet, Workbook, Shape, etc. (ex. rng)
  • Collection – Collection of objects (ex. Range(“a1:a10”)
  • [Do Something] – Code block to run on each object
  • Next [Object] – Closing statement. [Object] is optional, however strongly recommended.

For Each Cell in Range

This code will loop through each cell in a range:

Sub ForEachCell_inRange()

Dim cell As Range

For Each cell In Range("a1:a10")
    cell.Value = cell.Offset(0,1).Value
Next cell

End Sub

For Each Worksheet in Workbook

This code will loop through all worksheets in a workbook, unprotecting each sheet:

Sub ForEachSheet_inWorkbook()

Dim ws As Worksheet

For Each ws In Worksheets
    ws.Unprotect "password"
Next ws

End Sub

For Each Open Workbook

This code will save and close all open workbooks:

Sub ForEachWB_inWorkbooks()

Dim wb As Workbook

For Each wb In Workbooks
    wb.Close SaveChanges:=True
Next wb

End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

For Each Shape in Worksheet

This code will delete all shapes in the active sheet.

Sub ForEachShape()

Dim shp As Shape

For Each shp In ActiveSheet.Shapes
    shp.Delete
Next shp

End Sub

For Each Shape in Each Worksheet in Workbook

You can also nest For Each Loops. Here we will loop through all shapes in all worksheets in the active workbook:

Sub ForEachShape_inAllWorksheets()

Dim shp As Shape, ws As Worksheet

For Each ws In Worksheets
    For Each shp In ws.Shapes
        shp.Delete
    Next shp
Next ws

End Sub

For Each – IF Loop

As we’ve mentioned before, you can use an If statement within a loop, performing actions only if certain criteria is met.

This code will hide all blank rows in a range:

Sub ForEachCell_inRange()

Dim cell As Range

For Each cell In Range("a1:a10")
    If cell.Value = "" Then _
       cell.EntireRow.Hidden = True
Next cell

End Sub

VBA Do While Loop

The VBA Do While and Do Until (see next section) are very similar. They will repeat a loop while (or until) a condition is met.

The Do While Loop will repeat a loop while a condition is met.

Here is the Do While Syntax:

Do While Condition
[Do Something]
Loop

Where:

  • Condition – The condition to test
  • [Do Something] – The code block to repeat

You can also set up a Do While loop with the Condition at the end of the loop:

Do 
[Do Something]
Loop While Condition

We will demo each one and show how they differ:

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Do While

Here is the Do While loop example we demonstrated previously:

Sub DoWhileLoop()
    Dim n As Integer
    n = 1
    Do While n < 11
        MsgBox n
        n = n + 1
    Loop
End Sub

Loop While

Now let’s run the same procedure, except we will move the condition to the end of the loop:

Sub DoLoopWhile()
    Dim n As Integer
    n = 1
    Do
        MsgBox n
        n = n + 1
    Loop While n < 11
End Sub

VBA Do Until Loop

Do Until Loops will repeat a loop until a certain condition is met. The syntax is essentially the same as the Do While loops:

Do Until Condition
[Do Something]
Loop

and similarly the condition can go at the start or the end of the loop:

Do 
[Do Something]
Loop Until Condition

Do Until

This do Until loop will count to 10, like our previous examples

Sub DoUntilLoop()
    Dim n As Integer
    n = 1
    Do Until n > 10
        MsgBox n
        n = n + 1
    Loop
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Loop Until

This Loop Until loop will count to 10:

Sub DoLoopUntil()
    Dim n As Integer
    n = 1
    Do
        MsgBox n
        n = n + 1
    Loop Until n > 10
End Sub

Exit Do Loop

Similar to using Exit For to exit a For Loop, you use the Exit Do command to exit a Do Loop immediately

Exit Do

Here is an example of Exit Do:

Sub ExitDo_Loop()

Dim i As Integer
i = 1 

Do Until i > 1000
    If Range("A" & i).Value = "error" Then
        Range("A" & i).Select
        MsgBox "Error Found"
        Exit Do
    End If
    i = i + 1
Loop

End Sub

End or Break Loop

As we mentioned above, you can use the Exit For or Exit Do to exit loops:

Exit For
Exit Do

However, these commands must be added to your code before you run your loop.

If you are trying to “break” a loop that’s currently running, you can try pressing ESC or CTRL + Pause Break on the keyboard. However, this may not work.  If it doesn’t work, you’ll need to wait for your loop to end or, in the case of an endless loop, use CTRL + ALT + Delete to force close Excel.

This is why I try to avoid Do loops, it’s easier to accidentally create an endless loop forcing you to restart Excel, potentially losing your work.

More Loop Examples

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Loop Through Rows

This will loop through all the rows in a column:

Public Sub LoopThroughRows()
 
Dim cell As Range
 
For Each cell In Range("A:A")
    If cell.value <> "" Then MsgBox cell.address & ": " & cell.Value
Next cell
 
End Sub

Loop Through Columns

This will loop through all columns in a row:

Public Sub LoopThroughColumns()

Dim cell As Range

For Each cell In Range("1:1")
    If cell.Value <> "" Then MsgBox cell.Address & ": " & cell.Value
Next cell

End Sub

Loop Through Files in a Folder

This code will loop through all files in a folder, creating a list:

Sub LoopThroughFiles ()

Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer

Set oFSO = CreateObject("Scripting.FileSystemObject")

Set oFolder = oFSO.GetFolder("C:Demo)

i = 2

For Each oFile In oFolder.Files
    Range("A" & i).value = oFile.Name
    i = i + 1
Next oFile

End Sub

Loop Through Array

This code will loop through the array ‘arrList’:

For i = LBound(arrList) To UBound(arrList)
    MsgBox arrList(i)
Next i

The LBound function gets the “lower bound” of the array and UBound gets the “upper bound”.

Loops in Access VBA

Most of the examples above will also work in Access VBA. However, in Access, we loop through the Recordset Object rather than the Range Object.

Sub LoopThroughRecords()
   On Error Resume Next
   Dim dbs As Database
   Dim rst As Recordset
   Set dbs = CurrentDb
   Set rst = dbs.OpenRecordset("tblClients", dbOpenDynaset)
   With rst
      .MoveLast
      .MoveFirst
      Do Until .EOF = True
         MsgBox (rst.Fields("ClientName"))
        .MoveNext
     Loop
   End With
   rst.Close
   Set rst = Nothing
   Set dbs = Nothing
End Sub

0 / 0 / 0

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

Сообщений: 3

1

15.08.2014, 13:05. Показов 7000. Ответов 5


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

Добрый день, подскажите пожалуйста почему не правильно отрабатывает макрос?

Суть задачи, есть ячейки вида

7 3 Ане
_ 4 Саше
4 4 Диме
6 1 Леше
_ 4 Лере
1 1 Ивану

пустая ячейка означает это один и тот же товар но под разных покупателей. количество товара это сумма 3+4 = 7
но например ниже

4+1 это 5, а в ячейке написано 6, 1 товар значит ложится на склад, и макрос должен добавить пустую строку. вычислить остаток склада и дописать его. Должно получиться что то

3 3 Ане
4 4 Саше
4 4 Диме
1 1 Леше
4 4 Лере
1 1 склад
1 1 Ивану

Макрос работает, но выражение Else cell5.Offset(1, 0).EntireRow.Insert отрабатывает сразу. как бы относя его к первому оператору

Кликните здесь для просмотра всего текста

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
29
Sub Макрос1() 
 ' заполняет пустые ячейки выделенного диапазона
    Columns("D:D").Select
    Dim cell5 As Range, ra5 As Range
    ' ограничиваем выделенный диапазон используемой областью листа
   Set ra5 = Intersect(Selection, ActiveSheet.UsedRange)
 
    If ra5 Is Nothing Then
        MsgBox "В выделенном диапазоне нет пустых ячеек!", _
               vbExclamation, "Нечего заполнять"
    Else
        Application.ScreenUpdating = False    ' отключаем обновление экрана
 
        ' перебираем все ячейки в выделенном диапазоне
       For Each cell5 In ra5.Cells
            ' если ячейка не ранва соседней ячейке, делаем следующее
           If cell5.Value <> cell5.Offset(0, -1).Value Then
                                                         If Trim(cell5.Offset(1, -1)) = "" Then cell5.Offset(1, -1) = cell5.Offset(0, -1).Value - cell5.Value
                                                         Else
                                                         cell5.Offset(1, 0).EntireRow.Insert
                                                         'cell5.Insert Shift:=xlDown
                                                         cell5.Offset(1, -1).Value = cell5.Offset(0, -1).Value - cell5.Value
                                                         cell5.Offset(1, 0).Value = cell5.Offset(0, -1).Value - cell5.Value
                                                         End If
                                                         cell5.Offset(0, -1).Value = cell5.Value
      Next cell5
   End If
 
End Sub



0



Понравилась статья? Поделить с друзьями:
  • Vba excel for в обратном порядке
  • Vba excel for to переменная
  • Vba excel for random
  • Vba excel for loop cells
  • Vba excel for example