简体   繁体   中英

VBA to loop through values in column, place values in cell that affects formula, and copy and paste resultant formula to adjacent column

Not super knowledgeable with VBA, but I'm assuming/hoping this is a fairly simple question. I have a worksheet where column K has any values that can be input in cell E1. Cell B25 contains a simple formula (=$B$24-$B$8), but is affected by other formulas, which depend on the value in cell E1.

What I need is for E1 to be looped through with the values in column K and paste the calculated value in B25 in column L for each value in column K. I have 2 VBA codes that I'm working with, but neither of them are working exactly how we need them to.

Sub Check()
Dim c As Range, sh1 As Worksheet
Set sh1 = Sheets("Sheet1")
    For Each c In sh1.Range("K2", Cells(Rows.Count, "K").End(xlUp))
        sh1.Range("E1") = c.Value
        sh1.Range("B25", Cells(Rows.Count, "B").End(xlUp)).Copy
        sh1.Range("L2", Cells(Rows.Count, "L").End(xlUp)).PasteSpecial Paste:=xlPasteValues
         Next
End Sub

And

        Sub Check2()
    Dim sh1 As Worksheet, c As Range
    Set sh1 = Sheets("Sheet1")
        For Each c In sh1.Range("K2", sh1.Cells(Rows.Count, "K").End(xlUp))
            sh1.Range("E1") = c.Value
            sh1.Range("B25", sh1.Cells(Rows.Count, 2).End(xlUp).Offset(, 2)).Copy _
            sh1.Cells(Rows.Count, 12).End(xlUp)(2)
        Next

End Sub

The first code loops through E1 and posts the calculated value of B25 in cell L2 only, so there's no way for us to know which corresponding item in column K it's referencing.

The second code is closer. It posts the results of the formula in column L sequentially, but it recalculates for each instance of the looped column K value in E1, meaning that ultimately the result of the formula in B25 will post the results only corresponding to the final value of column K in column L (ie the formula =$B$24-$B$8 is copied and pasted down column L for every value in column K but the last value of column K will be in cell E1, so that's what the formula is referring to).

I might be going about this all wrong, but as mentioned, I don't deal with VBA a lot. I hope someone can help me with this, but please let me know if I was unclear in my request or anyone needs more information!

Try this.

Sub Check2()

Dim sh1 As Worksheet, c As Range

Set sh1 = Sheets("Sheet1")

For Each c In sh1.Range("K2", sh1.Cells(Rows.Count, "K").End(xlUp))
    sh1.Range("E1") = c.Value
    sh1.Range("B25", sh1.Cells(Rows.Count, 2).End(xlUp).Offset(, 2)).Copy
    sh1.Cells(Rows.Count, 12).End(xlUp)(2).PasteSpecial xlValues
Next

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