答案 0 :(得分:3)
假设Answer
出现在Price
和Discount
下方,以下内容应该会有所帮助。
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
注意: If cel.Value = "Price" Then
区分大小写,并且仅匹配Price
而非price
,同样适用于{ {1}}和ElseIf cel.Value = "Discount" Then
。