[英]Loop input values in another sheet through cell reference then Copy formula value and paste it to another sheet using vba
[英]VBA to loop through values in column, place values in cell that affects formula, and copy and paste resultant formula to adjacent column
對 VBA 不是很了解,但我假設/希望這是一個相當簡單的問題。 我有一個工作表,其中 K 列具有可以在單元格 E1 中輸入的任何值。 單元格 B25 包含一個簡單的公式 (=$B$24-$B$8),但受其他公式的影響,這些公式取決於單元格 E1 中的值。
我需要的是讓 E1 與 K 列中的值循環,並將 B25 中的計算值粘貼到 L 列中 K 列中的每個值。我有 2 個正在使用的 VBA 代碼,但它們都不是完全按照我們需要的方式工作。
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
和
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
第一個代碼循環遍歷 E1 並僅在單元格 L2 中發布 B25 的計算值,因此我們無法知道它引用了 K 列中的哪個對應項。
第二個代碼更接近。 它將公式的結果按順序發布在 L 列中,但它會重新計算 E1 中循環列 K 值的每個實例,這意味着最終 B25 中的公式結果將發布僅對應於列 K 的最終值的結果在 L 列中(即公式 =$B$24-$B$8 被復制並粘貼到 L 列,用於 K 列中的每個值,但 K 列的最后一個值將在單元格 E1 中,所以這就是公式所指的內容) .
我可能會在這一切都錯了,但如前所述,我不經常處理 VBA。 我希望有人能幫我解決這個問題,但如果我的請求不清楚或者有人需要更多信息,請告訴我!
嘗試這個。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.