if / then公式多行

时间:2016-05-24 04:08:42

标签: excel-vba vba excel

我正在尝试制作一个代码(对某些人来说很简单),但我缺乏经验并希望得到帮助。

查看单元格("J1")并为{" if / then")中的结果执行K1的代码,但我希望重复此查看范围J2 to J10单元格,以便在K2 to K10范围内提供结果。 以下代码适用于单行公式:

    Sub Check() 
        Dim DDDD As Date, result As String 
        DDDD = Range("j1").Value 
        If DDDD >= Date Then 
            result = "Future" 
        Else 
            result = "Now" 
        End If 
        Range("k1").Value = result 
   End Sub 

3 个答案:

答案 0 :(得分:0)

这是一段循环通过J列的代码,结果将放在K列。

Sub Check()

Dim DDDD As Date
Dim result As String
Dim row, NumofRows  As Integer

' use NumfofRows as a Dynamic value to decide how many rows of data you want to look at column J
NumofRows = 10

For row = 1 To NumofRows
    If Cells(row, 10) >= Date Then
        result = "Future"
    Else
        result = "Now"
    End If 
    Cells(row, 11).Value = result
Next

End Sub

答案 1 :(得分:0)

您可以使用For Each循环和Offset方法,如下所示:

 Sub Check() 
    Dim DDDD As Date, result As String 
    Dim cell as Range

    For Each cell in Range("J1:J10")
        DDDD = cell.Value 
        If DDDD >= Date Then 
            result = "Future" 
        Else 
            result = "Now"
        End If 
        ' Change value at the right side of the cell
        cell.Offset(0,1).Value = result 
    Next cell
End Sub 

但是使用VBA实在是太过分了。您可以将此公式放在K1

=IF(J1 >= TODAY(), "Future", "Now")

...然后将该公式复制/拖动到其下方的其他单元格。

答案 2 :(得分:0)

将来,请查看rules of etiquette,让您的问题既有趣又有吸引力。对于您的问题,处理Ranges而不是具有日期的单个单元格将更有效。 For Each...Next循环可循环遍历范围中的每个单元格。然后,If...Then...Else...End If循环可以根据各种条件做出决定。可以在Offset(0, 1)循环内使用If...Then方法将结果放在右侧的列中。以下代码执行您似乎要求的内容:

Sub Check()
'    Declare your variables
     Dim MyDates As Range
     Dim result As String

'    First, grab all the values in the J2:JX column, where
'    X can be any number of dates you choose. Note that
'    you must "Set" Object variables, but you must "Dim"
'    other types of variables. 
     Set MyDates = Range(Range("J2"), Range("J2").End(xlDown))

'    Loop through every cell in the dates column and give the
'    offset column (column K) a string value if the condition
'    is met.
     Dim Cell As Range
     For Each Cell In MyDates
         If Cell >= Date Then
             result = "Future"
             Cell.Offset(0, 1).Value = result
         Else
             result = "Now (or past)"
             Cell.Offset(0, 1).Value = result
         End If
     Next Cell
End Sub

End(xlDown)方法模拟选择单元格并按Ctrl +向下箭头。另请注意,此代码根本不处理错误。例如,如果您不小心输入日期为 text ,则该过程将产生不正确的结果。此外,根据您输入数据的时间,您可能会得到令人困惑的结果。我在这里附上了Excel中的结果图像:

My results in Excel with Form Control to execute VBA.