简体   繁体   中英

Excel VBA - populate cells in one column based on values in another one

First of all, sorry for being blunt - I'm just starting my adventure with coding, and I sort of stuck on the problem below...

I have a file in which there are product names and their prices. The names of the products are repetitive, and so are their prices. I would like to have a macro that would read the column contaning product names (B), and then copy the prices from column C, so that all products with the same name have the same price. After that, the macro should put zeroes in all rows contaning product name and price (columns D to F).

I've spent last two days wrapping my head around this idea, but the only thing I seem to get right is this bit:

price = Range("C2").Value
If price > 0 Then
Range("D2:F2") = 0
End If

I can repeat this for all rows, that's not a problem... but the first part of the problem eludes me by what seems to be light-years.

Is there a simple solution I've been missing?

What the file looks before:

What it should look like after:

Edit: I have also a terribly crude and cumbersome solution to copy the prices:

If Range("B5") = Range("B2") Then
Range("C2").Select
Range("C2").Copy
Range("C5").Select
Range("C5").PasteSpecial
End If

But I realze that this would require a constant number of products (not the case - can be 2, can be two dozen)... so I am not happy with that.

I made quickly just looking the photo what you are expecting, see if is like this.

    Dim vLR As Long, vC, l, c  'l = line and c= column

    vLR = Cells(Rows.Count, 1).End(xlUp).Row 'vLR =  variable Last Row

    vC = 0 'vC = variable Columns you have
    c = 4 ' starting on the 4 column
    Do While vC < 3 '3 columns availability /ordered/sold
        l = 2
        Do While vLR >= l
            If Cells(l, c) = "" Then
                Cells(l, c) = 0
            End If
            l = l + 1
        Loop
        c = c + 1
        vC = vC + 1
    Loop
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM