Problem with an equation.

  • Thread starter Thread starter jim simpson
  • Start date Start date
J

jim simpson

I'm using a macro to build an equation where "x" is an unknown. When
finished calculations will be performed and "x" will be assigned values.

The right side of the equation is a series. The first time throught the
progaam it builts the first element of the series like so:

q = s * exp(t*x)

The next time through it adds another element like so:

q = s * exp(t*x) + s * exp(t*x)...

and so on until it is finished.

Since "t" and "s" have diferent values in each element I want the equation
to use the actual values in each element but leave the "x" unassigned like
so:

q = 20.5817 * exp(22*x) + 62.4573 * exp(58*x)...

I've tried every way to get this to work but it always assumes "x" = 0 and
computes the equation.

Can someone help me?

Jim
 
Jim,
This approach might suit your needs. It builds each element of your
equation as a string and substitutes values of s and t.. When the last
element has been built, you can substitute y (cannot use x as the x in "exp"
will be changed!)

I haven't checked the maths!

Sub BuildEquation()
Dim qx()

str1 = "s * exp("
str2 = "t + y)"

For i = 1 To 5 <==== Change to suit you needs
sx = Rnd() * 100 ' Test value of s
tx = Int(Rnd() * 100) ' Test values of t
strA = Replace(str1, "s", sx)
strB = Replace(str2, "t", tx)
ReDim Preserve qx(i)
qx(i) = strA + strB
Next i

yx = 20 ' Subtitute value for y (x in your original)

q = 0
For i = 1 To UBound(qx)
strq = Replace(qx(i), "y", yx)
qVal = Evaluate(strq)
q = q + qVal
Next i

MsgBox q

End Sub


HTH
 
Modified version which builds a single equation:

Sub BuildEquation()

Dim qstr As String, str1 As String, str2 As String
Dim strA As String, strB As String

str1 = "s * exp("
str2 = "t + y)"

For i = 1 To 5

sx = Rnd() * 100
tx = Int(Rnd() * 100)

strA = Replace(str1, "s", sx)
strB = Replace(str2, "t", tx)

qstr = qstr + strA + strB & " + "

Next i

yx = 20 ' Replace y with this value

qstr = Left(qstr, Len(qstr) - 3)
qstr = Replace(qstr, "y", yx)

MsgBox qstr
MsgBox Evaluate(qstr)

End Sub
 
Back
Top