简单IF然后乘以VBA

时间:2017-10-04 03:55:50

标签: excel vba

enter image description here

我有一张如上图所示的表格,我只想要一个简单的代码,如果ID彼此相等,(1 = 1)那么它将返回底部的另一组行(Answer)将显示

answer = price * (1 + discount)

1 个答案:

答案 0 :(得分:3)

假设Answer出现在PriceDiscount下方,以下内容应该会有所帮助。

Sub Demo()
    Dim ws As Worksheet
    Dim lastRow As Long, i As Long
    Dim dictPrice As Object, dictDiscount As Object
    Dim rng As Range, cel As Range

    Set ws = ThisWorkbook.Sheets("Sheet1")      'change Sheet1 to your data sheet
    Set dictPrice = CreateObject("Scripting.Dictionary")
    Set dictDiscount = CreateObject("Scripting.Dictionary")

    With ws
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row    'get last row with data using Column A
        For Each cel In .Range("A2:A" & lastRow)            'loop though all cells in Column A
            If cel.Value = "Price" Then                     'check if its Price
                dictPrice.Add cel.Offset(0, 1).Value, cel.Offset(0, 3).Value    'add id and correspoding price in dictionary
            ElseIf cel.Value = "Discount" Then              'check if its Discount
                dictDiscount.Add cel.Offset(0, 1).Value, cel.Offset(0, 3).Value 'add id and correspoding discount in dictionary
            ElseIf cel.Value = "Answer" Then                'check if its Answer
                cel.Offset(0, 3).Value = dictPrice(cel.Offset(0, 1).Value) * (1 + dictDiscount(cel.Offset(0, 1).Value))
            End If
        Next cel
    End With
End Sub

enter image description here

注意: If cel.Value = "Price" Then区分大小写,并且仅匹配Price而非price,同样适用于{ {1}}和ElseIf cel.Value = "Discount" Then