Trying to solve an equation using excel-vba,
Equation: xy = 5(x+y)
I use the below vba code to determine the values of x
and y
and print it in cell A1
Sub equation()
Dim x As Long, y As Long
For x = 1 To 9
For y = 1 To 9
If ((x * y) = (5 * (x + y))) Then
Range("A1") = x & "," & y
End If
Next y
Next x
End Sub
However this code is not working. I guess I am missing something in the IF
condition.
I tried the below and this works perfectly,
Sub equation()
Dim x As Long, y As Long
For x = 1 To 9
For y = 1 To 9
If 5 * (x + y) = 45 Then
Range("A1") = x & "," & y
End If
Next y
Next x
End Sub
I even tried with 2 temp
variables, but doesn't works,
Sub equation()
Dim x As Long, y As Long, temp1 As Long, temp2 As Long
For x = 1 To 9
For y = 1 To 9
temp1 = x * y
temp2 = 5 * (x + y)
If temp1 = temp2 Then
Range("A1") = x & "," & y
End If
Next y
Next x
End Sub
Can someone tell me what I am doing wrong with the IF
condition.
答案 0 :(得分:4)
Consider:
xy = 5(x+y)
xy = 5x+5y
xy-5y = 5x
y(x-5) = 5x
y = 5x/(x-5)
Then just plug in values for x and solve for y
Sub qwerty()
Dim x As Long, y As Long
For x = 6 To 13
y = 5 * x / (x - 5)
Cells(x, 1) = x
Cells(x, 2) = y
Next x
End Sub
Pick any values for x, just avoid x = 5
.
Declare y
as Double if you require the fractional part: