mercredi 9 septembre 2015

Multiply multiple columns based on if then logic

I'm trying to formulate vba logic that will multiply cells in one column by other columns based on the header name. For example if I have the data below: enter image description here

In column I, I'm trying to multiply cell range A2:A11 by B2:B11 by D2:D11. Since the value in A1 is the same as the left two characters in D1 and B1 is the same as the right two characters in D1. In column J it would be cell range A2:A11 multiply by E2:E11 and so on. The result should look as follows: enter image description here

The macro is attempting to do this by comparing the cell values in cell rage A1:B1 to D1:G1, but what I cannot figure out is how to multiply 3 cell ranges together.

Vba:

Sub IfThenLogic2()
Dim SrchRng1 As Range, cel1 As Range
Dim SrchRng2 As Range, cel2 As Range

Set SrchRng1 = Sheets("Sheet2").Range("A1:B1")
Set SrchRng2 = Sheets("Sheet2").Range("F1:G1")


c = 13

For Each cel1 In SrchRng1

    For Each cel2 In SrchRng2
    If (cel1.Value = Left(cel2.Value, 2) Or cel1.Value = Right(cel2.Value, 2)) Then
    'If cel1.Value = cel2.Value Then
        For r = 2 To 11
            Cells(r, c).FormulaR1C1 = "=" & cel1.Offset(r - 1, 0).Address(ReferenceStyle:=xlR1C1) & "*" & cel2.Offset(r - 1, 0).Address(ReferenceStyle:=xlR1C1) & ""
        Next r
        c = c + 1
        End If
    Next cel2
Next cel1


End Sub

The OR operator produces (as expected): enter image description here

Is there perhaps a better way to accomplish this by not using for each loops? Thanks for any suggestions!

Aucun commentaire:

Enregistrer un commentaire