【问题标题】:Running total loop within loop in vba在vba中的循环内运行总循环
【发布时间】:2021-03-18 08:12:54
【问题描述】:

我试图让底部的循环每次将值 m 增加 m。例如,如果 m = .002,我希望它从 week_start 到 53 的每个单元格增加 .002。我尝试用我的“减少”变量来做到这一点。

如果您知道如何在每次迭代中添加一个循环,但仅针对我的变量 m,请告诉我。

谢谢!

Sub decrease_projections()
Dim pd As Worksheet
Dim p As Double
Dim week_start As Integer

Set pd = Worksheets("CSD_Proj_Data")

'clear contents for new values
pd.Range("R2:R53").ClearContents

'reset projected values
For i = 11 To 53 Step 1

pd.Cells(i, 18) = pd.Cells(i + 253, 4)

Next i

'get input
p = Val(InputBox("Enter percentage to decrease projections over time gradually.", "Decrease Projections", (0))) / 100
w = Val(InputBox("Enter week to begin decrease.", "Decrease Projections"))

w = Trim(w)

pd.Range("z1") = w

week_start = pd.Range("AA1")

'calculate percentage loss
m = p / 30

'for loop to calculate decreased sales projections
    
For i = week_start To 53 Step 1

    decrease = m * (53 - week_start)
    d = pd.Cells(i, 18) * (1 - decrease)
    pd.Cells(i, 18) = d
            
Next i

'pd.PivotTables("PivotTable1").PivotCache.Refresh

End Sub

【问题讨论】:

  • 引入另一个Dim loopCount As Long 变量。在循环开始之前将其初始化为loopCount = 1,然后是decrease = m * (53 - week_start) * loopCountloopCount = loopCount + 1。这应该会随着循环的每次迭代增加您的 decrease 值。
  • 这是否意味着围绕我拥有的循环创建一个循环并让它计数?然后在我当前的循环中让它乘以计数?谢谢

标签: excel vba loops


【解决方案1】:

我相信您要问的是在每个循环中增加您的 decrease 值。下面是一个示例,说明如何创建变量以在每次迭代时修改值。

'for loop to calculate decreased sales projections
Dim loopCount As Long
loopCount = 1
For i = week_start To 53 Step 1
    decrease = m * (53 - week_start) * loopCount
    d = pd.Cells(i, 18) * (1 - decrease)
    pd.Cells(i, 18) = d
    loopCount = loopCount + 1
Next i

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 2014-06-27
    • 1970-01-01
    • 2015-03-24
    相关资源
    最近更新 更多