tl1234
tl1234

Reputation: 3

VBA: How do call out minimum coordinate out of if function?

How do I print the i and j (x,y) coordinates as msgbox?

Sub Length_Min()
    'Define variables where length and maximum lengths are integers'
    Dim Length_Max As Double, Length As Double

    'Comparing Variable, set maximum length to 1000m'
    Length_Max = 1000

    'Double for loop, within domain with increment of 0.01m.'
    'Domain x[i] : 0<=x<=50 and Domain y[j]: 0<=y<=30'
    For i = 0 To 50 Step 0.01
        For j = 0 To 30 Step 0.01

            'Subsitute x-values [i] and y- values [j] into the Total Length equation, Length.'
            Length = (Sqr((5 - i) ^ 2 + (5 - j) ^ 2)) + (Sqr((10 - i) ^ 2 + (20 - j) ^ 2)) + (Sqr((30 - i) ^ 2 + (10 - j) ^ 2))

            'If the length found from the equation Length [L(x,y)] is less than 1000, then replace Length Max with new Length found.'
            'Repeat for all increments of 0.01m untill smallest L(x,y) is found.'
            If Length < Length_Max Then Length_Max = Length

        Next j
    Next i

    'Print the minimum length found and its (x,y) coordinates, point P'
    MsgBox "The minimum length is : " & Length_Max & " meters" & vbNewLine & "Minimum x and y coordinates are : " & i & " , " & j
End Sub

Upvotes: 0

Views: 53

Answers (1)

YowE3K
YowE3K

Reputation: 23974

You will need to keep a record of the value of i and j when the minimum occurs:

Sub Length_Min()
    'Define variables where length and maximum lengths are integers'
    Dim Length_Max As Double, Length As Double
    Dim iMin As Double
    Dim jMin As Double

    'Comparing Variable, set maximum length to 1000m'
    Length_Max = 1000

    'Double for loop, within domain with increment of 0.01m.'
    'Domain x[i] : 0<=x<=50 and Domain y[j]: 0<=y<=30'
    For i = 0 To 50 Step 0.01
        For j = 0 To 30 Step 0.01

            'Subsitute x-values [i] and y- values [j] into the Total Length equation, Length.'
            Length = (Sqr((5 - i) ^ 2 + (5 - j) ^ 2)) + (Sqr((10 - i) ^ 2 + (20 - j) ^ 2)) + (Sqr((30 - i) ^ 2 + (10 - j) ^ 2))

            'If the length found from the equation Length [L(x,y)] is less than 1000, then replace Length Max with new Length found.'
            'Repeat for all increments of 0.01m untill smallest L(x,y) is found.'
            If Length < Length_Max Then
                Length_Max = Length
                iMin = i
                jMin = j
            End If
        Next j
    Next i

    'Print the minimum length found and its (x,y) coordinates, point P'
    MsgBox "The minimum length is : " & Length_Max & " meters" & vbNewLine & "Minimum x and y coordinates are : " & iMin & " , " & jMin
End Sub

Upvotes: 2

Related Questions