跨列的目标搜寻宏扫描

时间:2018-12-14 20:47:11

标签: excel vba

Recently, I asked how to write a macro that will loop goal seek when its organized in rows.我现在想跨列循环目标搜索。到目前为止,我有以下代码。

Sub Goal_Seek()
    Dim lastcol As Long, i As Long

    With ActiveSheet
        lastcol = .Cells(.Columns.Count, "4").End(xlToLeft).Column

        For i = K To lastcol
            .Range(i & "4").GoalSeek Goal:=0, ChangingCell:=.Range(i & "4")
        Next i
    End With
End Sub

这是我的Excel。 Spreadsheet with data in K4:N6

我想通过更改K4将“方差”设置为零。然后,我希望宏向右移动一列,并继续进行目标搜索,直到最后。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

i应该是Long,而不是字母,并使用Cells而不是Range。请注意,Cells 1st 参数是行索引,而 2nd 是列索引。

Sub Goal_Seek()
    Dim lastcol As Long, i As Long

    With ActiveSheet
        lastcol = .Cells(4, .Columns.Count).End(xlToLeft).Column

        For i = 11 To lastcol
            .Cells(6, i).GoalSeek Goal:=0, ChangingCell:=.Cells(4, i)
        Next i
    End With
End Sub