Willarci3
Willarci3

Reputation: 55

'If ... Then' statement with loop

I've what seems like a pretty simple application with looping and 'If..Then' statements but need some help on structuring it.

In very a basic example, I have a list numbers in column A and the values PM or AM listed in column B. I want to write a loop that will search every value in column B until the end of the data set, and add 12 to each value in column A each time column B has a value of PM. In a nutshell, it would look like this:

Upvotes: 0

Views: 45251

Answers (3)

user5412293
user5412293

Reputation:

This is another way to do this.

Option Explicit

Sub Add()
    Dim rData As Range
    Dim r As Range

    Set rData = Cells(1, 1).CurrentRegion.Columns("B").Cells

    For Each r In rData
        If UCase$(r.Value) = "PM" Then
            r.Offset(, -1).Value = r.Offset(, -1).Value + 12
        End If
    Next r
End Sub

Upvotes: 0

Balinti
Balinti

Reputation: 1534

you can set it with For next loop and 2 variables. one for last row and the 2nd for the row count:

   Sub Macro1()

        Dim LastRow As String
        Dim i As Integer
        LastRow = Cells(Rows.Count, "A").End(xlUp).Row
        For i = 1 To LastRow
        If Cells(i, 2).Value = "PM" Then Cells(i, 1).vlaue = Cells(i, 1).vlaue + 10
        Next i
        End

        '
        End Sub

Upvotes: 0

Gary's Student
Gary's Student

Reputation: 96753

There are many ways, here is a typical one:

Sub dural()
   Dim i As Long

   i = 1
   Do While Cells(i, "B").Value <> ""
      If Cells(i, "B").Value = "PM" Then
            Cells(i, "A").Value = Cells(i, "A").Value + 12
      End If
      i = i + 1
   Loop
End Sub

Upvotes: 5

Related Questions