Need help with an error I keep getting in Excel VBA

I keep getting a byref type mismatch error whenever I try to run this program. It is supposed to find the zeros of the equation f(x)=3x^2+ln(x) through the bisection method. I have to find the zeros, and number of iterations it takes to get it. This is what I have so far and I'd appreciate it if someone could point out my mistakes.

Option Explicit
Function bisection_equation(n As Double) As Double
bisection_equation = 3 * (n ^ 2) + Log(n)
End Function
Sub bisection()
Dim x_low, x_high, x_guess, diff As Double
Dim i As Integer
x_low = Application.InputBox("Left Bound?", Type:=1)
x_high = Application.InputBox("Right Bound?", Type:=1)
i = 1
Do
diff = x_guess
x_guess = (x_high + x_low) / 2
If bisection_equation(x_guess) < 0 Then
If bisection_equation(x_low) < 0 Then
x_low = x_guess
Else: bisection_equation (x_low) > 0
x_high = x_guess
End If
ElseIf bisection_equation(x_guess) > 0 Then
If bisection_equation(x_low) < 0 Then
x_high = x_guess
Else: bisection_equation (x_low) > 0
x_low = x_guess
End If
End If
i = i + 1
Loop Until Abs(diff - x_guess) / x_guess < 0.000001
MsgBox "The zero is at: " & x_guess
End Sub

andycr's picture

Misuse of DIM

Hi, your problem is a typical misuse of the Dim Declaration.

Dim x_low, x_high, x_guess, diff As Double

should be

Dim x_low As Double, x_high As Double, x_guess As Double, diff As Double

note that the " As Double" you have only applies to the last variable you declared.

:-)

Nick's picture

you don't say where you're

you don't say where you're getting the type mismatch, but my guess is that it's from the inputs..

try changing this:
x_low = Application.InputBox("Left Bound?", Type:=1)
x_high = Application.InputBox("Right Bound?", Type:=1)

to this:
dim UserInput as variant
UserInput = Application.InputBox("Left Bound?", Type:=1)
x_low = cdbl(UserInput) ' line 1
UserInput = Application.InputBox("Right Bound?", Type:=1)
x_high = cdbl(UserInput) ' line 2

if it errors on line 1 or line 2, then it's not able to cast the input to a double