【问题标题】:How to create an If Loop如何创建一个 If 循环
【发布时间】:2018-03-29 12:55:13
【问题描述】:

我有 2 列需要比较美元的付款金额。数据来自两个不同的来源,但它们应该匹配。每个月都有不同的付款次数,所以我不知道下次会有 20 次还是 30 次。所以我需要比较这两个列。我想要做的是使用 if 函数

If [n3] = [u3] Then
    [q3] = "yes"
Else
    [q3] = "no"
End If

而且我不知道如何在每次付款时使用循环来执行此操作。

【问题讨论】:

  • 看看for next loop find last cell in range vba 还是只使用Q中的公式?
  • google For Loops vbafind last cell with data in column vba 使用该信息尝试构建正确的循环。当您遇到困难时,请重新尝试并解释错误。
  • 请注意,它们被称为 loops,而不是 cycles。您真的想要在 VBA 中执行此操作,还是更愿意使用工作表公式使其更简单?
  • 感谢您的回答,我会检查您的建议。 ashleedawg 是的,它会更容易,但它比这更复杂,所以我想将它包含在整个代码中。会更干净。
  • 好的,有什么限制? (即,最小和最大行/列在什么条件下应该有这个公式?)

标签: vba loops if-statement


【解决方案1】:
  1. 计算从单元格开始的值的行数的函数(定义为Range对象)

    Public Function CountRows(ByVal r As Range) As Long
        If IsEmpty(r) Then
            CountRows = 0
        ElseIf IsEmpty(r.Offset(1, 0)) Then
            CountRows = 1
        Else
            CountRows = r.Worksheet.Range(r, r.End(xlDown)).Rows.Count
        End If
    End Function
    
  2. 您希望进行检查的工作表代码中的示例用法。

    Public Sub CheckPayments()
        Dim rn as Range, ru as Range, rq as Range
        'One price column & first value
        Set rn = Range("N3")
        'Otjher price column & first value
        Set ru = Range("U3")
        ' Check result column & first value
        Set rq = Range("Q3")
    
        Dim i as Long, n as Long
        ' Count non-empty cells below "N3"
        n = CountRows(rn)
    
        'Loop through rows
        For i = 1 to n
            ' Check for matching values
            If rn.Cells(i,1).Value = ru.Cells(i,1).Value Then
                rq.Cells(i,1).Value = "yes"
            Else
                rq.Cells(i,1).Value = "no"
            End If
        Next i
    End Sub
    

【讨论】:

    猜你喜欢
    • 2017-04-05
    • 2021-04-30
    • 2022-07-12
    • 2013-08-05
    • 2023-03-17
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 2021-04-23
    相关资源
    最近更新 更多