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

求助编写Excel VBA循环代码,实现财务模型假设敏感性分析

财务模型敏感性分析VBA解决方案

原代码的问题

  • VBA的For循环语法错误,正确写法是 For i = 1 To 6,不是冒号分隔
  • 单元格区域赋值不能直接用=,要使用.Value属性或者Copy方法
  • 没有保存初始假设值,循环结束后D列会停留在最后一组假设值,无法恢复初始状态
  • 循环缺少Next i语句,导致代码无法正常执行
  • VBA中调用无参数方法不需要加括号,inputVariables.Clear()应该写成inputVariables.Clear

修正后的完整代码

Sub SensitivityAnalysis()
    ' 定义变量
    Dim inputVariables As Range
    Dim inputSet As Range
    Dim initialVariables As Variant
    Dim outputRange As Range
    Dim outputTable As Range
    Dim i As Integer
    
    ' 设定各个区域范围
    Set inputVariables = Worksheets("Assumption sheet").Range("D8:D235")
    ' 把M到R列的每组假设值按列拆分,方便循环调用
    Set inputSet = Worksheets("Assumption sheet").Range("M8:R235")
    Set outputRange = Worksheets("Output sheet").Range("I28:I57")
    Set outputTable = Worksheets("Output sheet").Range("K28:P57")
    
    ' 保存初始假设值,循环结束后恢复
    initialVariables = inputVariables.Value
    
    ' 循环处理6组假设值(M到R列对应i=1到6)
    For i = 1 To 6
        ' 替换D列为当前组的假设值
        inputVariables.Value = inputSet.Columns(i).Value
        ' 计算后把输出结果写入对应列
        outputTable.Columns(i).Value = outputRange.Value
    Next i
    
    ' 恢复初始假设值
    inputVariables.Value = initialVariables
End Sub

关键说明

  • 保存初始值:用initialVariables = inputVariables.Value把D列初始值存到变量里,循环结束后再赋值回去,避免破坏原始数据
  • 列操作:inputSet.Columns(i)直接取第i列的假设值,outputTable.Columns(i)对应写入第i列的输出结果,确保每组假设和输出一一对应
  • 赋值逻辑:用.Value属性直接传递单元格区域的值,比Copy方法更高效,适合批量数据传递

内容的提问来源于stack exchange,提问作者Jonas de Boo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 11:17:30