vba 'If ... Then' 循环语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33001548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:00:59  来源:igfitidea点击:

'If ... Then' statement with loop

excelvbaexcel-vbaloopsif-statement

提问by Willarci3

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

我有一个看起来很简单的应用程序,带有循环和“If..Then”语句,但在构建它时需要一些帮助。

In very a basic example, I have a list numbers in column A and the values PMor AMlisted 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 12to each value in column A each time column B has a value of PM. In a nutshell, it would look like this:

在非常基本的例子,我在A列的列表号和值PMAM在列B我想列出来写一个循环,将搜索B列中的每个值,直到数据集的结尾,并添加12到每个值在 A 列中,每次 B 列的值为PM。简而言之,它看起来像这样:

  • If column B = PM
  • then add 12to its corresponding cell in column A
  • else move down to the next row and do the same thing until you reach an empty cell
  • 如果 B 列 = PM
  • 然后添加12到 A 列中的相应单元格
  • 否则向下移动到下一行并执行相同的操作,直到到达一个空单元格

回答by Gary's Student

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

回答by Balinti

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

您可以使用 For next 循环和 2 个变量来设置它。一个用于最后一行,第二个用于行数:

   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

回答by Balinti

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