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

VBA循环列调用GoalSeek函数时出现运行时错误'13'类型不匹配

解决VBA GoalSeek循环时的运行时错误'13':类型不匹配

错误原因

代码中Cells(234, Columns(i))这类写法存在本质问题:Cells方法的列参数需要是数字或列标字符串,但Columns(i)返回的是一个Range对象(比如第5列的整列区域),将Range对象作为列参数传入会直接触发类型不匹配错误。

修正后的代码

Private Sub GoalSeek1()
    'For testing purposes only
    MsgBox "GoalSeek1"
    
    'Defining variable i
    Dim i As Integer
    'Defining column count. Cell holds a number value
    Dim controlCell As Integer
    controlCell = Range("C14").Value ' 显式获取单元格数值,避免隐式转换问题
    
        'Looping through column 5 to target of (column 5 + controlCell)
        For i = 5 To (5 + controlCell)
            ' 直接用i作为列索引,符合Cells方法参数要求
            Cells(234, i).GoalSeek Goal:=Cells(240, i).Value, ChangingCells:=Cells(164, i)
        Next i
    
End Sub

关键修改点

  • 替换Columns(i)为i:i是列的数字索引,完全符合Cells方法对列参数的类型要求。
  • 增加.Value显式取值:给Range("C14")和Cells(240, i)加上.Value,明确获取单元格的数值,避免因单元格格式、公式等因素导致的隐式类型转换异常。

额外注意事项

循环范围5 To (5 + controlCell)需要确认是否匹配你的实际需求:比如若controlCell值为3,当前循环会覆盖第5、6、7、8列(共4列),如果你的需求是从第5列开始,共处理controlCell列,应改为5 To (5 + controlCell - 1),避免多循环一列。

内容的提问来源于stack exchange,提问作者Keith K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:35:23