You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA:如何将Do While循环结果作为下一次循环输入

解决VBA循环中结果传递的问题

你的核心问题是列循环时没有将上一次计算的EndV赋值给StartV,导致每次都用初始的E列值进行减法,无法实现连续递减的计算逻辑。

修改思路

在列循环的每次迭代中,计算完EndV = StartV - UseV后,立即将StartV更新为当前的EndV,这样下一次循环就会用上一轮的结果作为新的输入值。

修改后的完整代码

r = 5
c = 6

Dim UseV As Long
Dim StartV As Long
Dim EndV As Long

Do While r <= LastFCrow2 ' 循环处理所有行(每4行一组)
    If FCws.Cells(r, 2).Value <> PrevYM And FCws.Cells(r, 4).Value <> 0 And FCws.Cells(r, 3).Value = "PldOrd" Then
        StartV = FCws.Cells(r, 5).Value ' 初始化当前行的起始值(E列)
        
        Do While c <= LastFCcol ' 循环处理当前行的列(从F列到W列)
            UseV = FCws.Cells(r, c).Value
            EndV = StartV - UseV
            
            ' 【关键修改】将当前EndV赋值给StartV,供下一次列循环使用
            StartV = EndV
            
            If EndV > 0 Then ' 剩余量大于0,继续下一列,添加顶部边框
                With FCws.Cells(r, c).Borders(xlEdgeTop)
                    .LineStyle = xlContinuous
                    .ColorIndex = xlAutomatic
                    .TintAndShade = 0
                    .Weight = xlThin
                End With
            End If
            
            If EndV < 0 Then ' 剩余量小于0,当月耗尽,添加对角线边框并退出列循环
                With FCws.Cells(r, c).Borders(xlDiagonalDown)
                    .LineStyle = xlContinuous
                    .ColorIndex = xlAutomatic
                    .TintAndShade = 0
                    .Weight = xlThin
                End With
                Exit Do
            End If
            
            If EndV = 0 Then ' 剩余量等于0,月末耗尽,添加顶部和右侧边框并退出列循环
                With FCws.Cells(r, c).Borders(xlEdgeRight)
                    .LineStyle = xlContinuous
                    .ColorIndex = xlAutomatic
                    .TintAndShade = 0
                    .Weight = xlThin
                End With
                With FCws.Cells(r, c).Borders(xlEdgeTop)
                    .LineStyle = xlContinuous
                    .ColorIndex = xlAutomatic
                    .TintAndShade = 0
                    .Weight = xlThin
                End With
                Exit Do
            End If
            
            c = c + 1
        Loop
        c = 6 ' 重置列指针到F列,处理下一行
    End If
    r = r + 4 ' 跳转到下一组的起始行(每4行一个产品)
Loop

关键说明

  • 新增的StartV = EndV语句确保了每次列循环都继承上一次的计算结果,实现E5-F5→(E5-F5)-G5→...的连续计算逻辑。
  • 保留了你原有的行循环逻辑(每次跳4行)和边框格式化规则,仅针对结果传递问题进行修复。

内容的提问来源于stack exchange,提问作者Nota G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:39:20