Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA GoalSeek Loop Issue

Tags:

loops

excel

vba

I am a novice regarding VBA and in my first code I try to make a loop through 2 columns (P and J) for a GoalSeek function.

The set cells are P2 then P3 then P4 etc. While the change cells are J2 then J3 etc.

I want to iterate from row 2 till row N (the number N is stored in the cell D1)

Here's what I wrote:

N = ThisWorkbook.Sheets("Reverse DCF").Range("D1").Value

Dim i As Integer

For i = 2 To N
     Range(Cells((i), "P")).GoalSeek Goal:=0, ChangingCell:=Range(Cells((i), "J"))
Next i

I get an error message:

 "Method 'Range' of object '_Global' failed.

I am sorry but I don't see the problem with my code.

like image 442
Rom M Avatar asked Mar 31 '26 15:03

Rom M


1 Answers

You can use Cells without Range. Here is an working example. Make sure cell Ncontains an integer and Pi to PN contains formulas.

Sub GoalSeekTest()

Dim N As Integer
Dim i As Integer

N = ThisWorkbook.Sheets("Reverse DCF").Range("D1").Value

    For i = 2 To N
        If Cells(i, "P").HasFormula Then
            'Messagebox for clarification
            MsgBox ("Formula cell: " & Cells(i, "P") _
                .Address(RowAbsolute:=False, ColumnAbsolute:=False))

            Cells((i), "P").GoalSeek Goal:=0, ChangingCell:=Cells((i), "J")
        Else
            MsgBox "Cell " & Cells(i, 1) _
                .Address(RowAbsolute:=False, ColumnAbsolute:=False) _
                & " has no formula - skipping this cell!", _
                vbCritical, "Formula required!"
        End If
    Next i
End Sub
like image 69
Sven Rojek Avatar answered Apr 02 '26 14:04

Sven Rojek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!