Excel VBA - 基于从x到y的输入单元格输出单元格公式(列表)

时间:2017-12-06 21:15:18

标签: excel vba excel-vba

我正在尝试在excel中完成以下操作并相信我需要使用VBA。任何帮助将不胜感激!

Excel输入

Cell A1 = A2*B2*C2
A2 ranges from x to y
B2 ranges from x to y
C2 ranges from x to y

Excel输出

Original Inputs, Formula Calculation (vertical list)

A2 B2 C2 , A1

1 个答案:

答案 0 :(得分:0)

我认为以下代码可以帮助您:

Sub foo2()
Dim A2(), B2(), C2() As Variant 'Declare the variables as Variant arrays
Dim LastRowA, LastRowB, LastRowC As Long

LastRowA = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row 'find the last row with data on column A
LastRowB = Sheet1.Cells(Rows.Count, "B").End(xlUp).Row 'find the last row with data on column B
LastRowC = Sheet1.Cells(Rows.Count, "C").End(xlUp).Row 'find the last row with data on column C

A2 = Sheet1.Range("A1:A" & LastRowA) 'take all values form A1 to the last row in that column into the A2 array
B2 = Sheet1.Range("B1:B" & LastRowB)
C2 = Sheet1.Range("C1:C" & LastRowC)

For x = LBound(A2) To UBound(A2) 'loop from the begining of the array until the end
    Sheet1.Cells(x, 6).Value = A2(x, 1) 'enter the values of A2 into the column F which is the number 6
    Sheet1.Cells(x, 7).Value = B2(x, 1) 'edit this values to "paste" the values wherever you wish
    Sheet1.Cells(x, 8).Value = C2(x, 1)
    Sheet1.Cells(x, 9).FormulaR1C1 = "=RC[-3]*RC[-2]*RC[-1]" 'this will enter the formula in those cells
Next x
End Sub