VBA:如何调出if函数的最小坐标?

时间:2017-05-03 08:18:23

标签: vba excel-vba math excel

如何将i和j(x,y)坐标打印为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

1 个答案:

答案 0 :(得分:2)

在最低限度发生时,您需要记录ij的值:

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