根据列和单元格之间的差异创建并循环列
Create and loop a column which is based on the difference between a column and a cell
我需要在循环中创建一个列,其中包含列和单元格 (A3) 之间的差异。
例如,在图片中,我想知道影响 1 与 H3 到 H.. = 场景(F3 到 F...)- A3 和影响 2= 场景 2(G3...G)-例如 A3 x 年 (B3)。
我从一个 if 循环开始,但我很难循环整个专栏。
Sub Lab1()
Dim i As Integer
If i <= Range("B3").Value Then
Range("H3").Value = Range("F3").Value - Range("A3").Value
Range("J3").Value = Range("G3").Value - Range("A3").Value
End If
i = 2020 + Range("B5").Value
End Sub
我不太确定代码中的 P 列在屏幕截图中的作用,但我认为这应该大致符合您的要求。如果您 运行 遇到任何问题,请告诉我们!
Sub loop1()
'define variables to work with
Dim ws As Worksheet
Dim interCol As Long, scen1Col As Long, impact1Col As Long
Dim firstRow As Long, lastRow As Long
Dim rng As Range
Dim intervention As Long, scenario As Long
Dim i As Long
'define current worksheet
Set ws = ActiveSheet
'define column numbers
interCol = 1 'A
scen1Col = 6 'F
impact1Col = 8 'H
'define start row
firstRow = 3
'end row is the last non-blank cell in Scenario 1 column
lastRow = ws.Cells(ws.Rows.Count, scen1Col).End(xlUp).Row
'loop from first row to last row
For i = firstRow To lastRow
'define cell to update
Set rng = ws.Cells(i, impact1Col)
'intervention doesn't change from row to row
intervention = ws.Cells(firstRow, interCol)
'scenario varies from row to row
scenario = ws.Cells(i, scen1Col)
'update target cell with calculation
rng = scenario - intervention
Next i
End Sub
我需要在循环中创建一个列,其中包含列和单元格 (A3) 之间的差异。
例如,在图片中,我想知道影响 1 与 H3 到 H.. = 场景(F3 到 F...)- A3 和影响 2= 场景 2(G3...G)-例如 A3 x 年 (B3)。
我从一个 if 循环开始,但我很难循环整个专栏。
Sub Lab1()
Dim i As Integer
If i <= Range("B3").Value Then
Range("H3").Value = Range("F3").Value - Range("A3").Value
Range("J3").Value = Range("G3").Value - Range("A3").Value
End If
i = 2020 + Range("B5").Value
End Sub
我不太确定代码中的 P 列在屏幕截图中的作用,但我认为这应该大致符合您的要求。如果您 运行 遇到任何问题,请告诉我们!
Sub loop1()
'define variables to work with
Dim ws As Worksheet
Dim interCol As Long, scen1Col As Long, impact1Col As Long
Dim firstRow As Long, lastRow As Long
Dim rng As Range
Dim intervention As Long, scenario As Long
Dim i As Long
'define current worksheet
Set ws = ActiveSheet
'define column numbers
interCol = 1 'A
scen1Col = 6 'F
impact1Col = 8 'H
'define start row
firstRow = 3
'end row is the last non-blank cell in Scenario 1 column
lastRow = ws.Cells(ws.Rows.Count, scen1Col).End(xlUp).Row
'loop from first row to last row
For i = firstRow To lastRow
'define cell to update
Set rng = ws.Cells(i, impact1Col)
'intervention doesn't change from row to row
intervention = ws.Cells(firstRow, interCol)
'scenario varies from row to row
scenario = ws.Cells(i, scen1Col)
'update target cell with calculation
rng = scenario - intervention
Next i
End Sub