首页 > 解决方案 > 在公式中插入变量

问题描述

我有一个单元格,其中包含以下内容:

=$H$10+1&","&B5+I10&","&(2*$D$2+$E$2)/2

此公式的结果采用以下格式:

14649,28.25,5.5

我想使用公式 VBA 代码。我希望1in 中的数字$H$10+**1**&"是 for 循环的 i 并且I10in"&B5+I10&"也随着循环而变化。

For i=1 to lastrow
.Range("X" & 13+i & "").Formula = "=$H$10+" & i & "" & "," & "B5+I" & i + 10 & "" & "," & "(2*$D$2+$E$2)/2"
Next i

标签: excelvba

解决方案


这里可以使用的代码:

Sub mySub()
    '=$H$10+1&","&B5+I10&","&(2*$D$2+$E$2)/2
    Dim myRange As Range
    Set myRange = Range("H:H").SpecialCells(xlCellTypeLastCell)
    Dim myStr As String
    'A=10 is for assigning first row in H as your data, hope no data upward from row 9 to row 1

    For Baris = 10 To myRange.Row
        On Error Resume Next
        myStr = "=$H$10+" & Baris - 9 & "&"",""&B5+I" & Baris & "&"",""&(2*$D$2+$E$2)/2"
        Range("K" & Baris).Formula = myStr

    Next
End Sub

推荐阅读