VBA Code: Conversion Calculator of Pressure and Temperature Using Bisection Method

VBA Code use in Userform: First make Useform:



Change name
textbox1: txtPressure
ComboBox: cmbTemperature
textbox2: lblResult

Button Name
Calculate: btnCalculate
Reset: CommandButtonReset
Quit: CommandButtonQuit

Now Right click on UseFrom to View Code:

Now Copy and Paste this below Code:

Option Explicit

Private Sub UserForm_Initialize()
    ' Populate the temperature ComboBox
    cmbTemperature.List = Array("300", "400", "450", "500", "550", "600")
End Sub

Private Sub btnCalculate_Click()
    ' Handle input validation and perform the bisection method
    
    ' Input validation for pressure
    If Trim(txtPressure.Value) = "" Then
        MsgBox "Please enter a pressure value.", vbExclamation
        Exit Sub
    ElseIf Not IsNumeric(txtPressure.Value) Then
        MsgBox "Pressure must be a numeric value.", vbExclamation
        Exit Sub
    ElseIf CDbl(txtPressure.Value) < 0.001 Or CDbl(txtPressure.Value) > 1000 Then
        MsgBox "Pressure must be between 0.001 and 1000 bar.", vbExclamation
        Exit Sub
    End If
    
    ' Get selected temperature and assign corresponding Ke value
    Dim selectedTemperature As Integer
    selectedTemperature = CInt(cmbTemperature.Value)
    
    Dim Ke As Double
    Select Case selectedTemperature
        Case 300: Ke = 0.00434
        Case 400: Ke = 0.000164
        Case 450: Ke = 0.0000451
        Case 500: Ke = 0.0000145
        Case 550: Ke = 0.00000538
        Case 600: Ke = 0.00000225
    End Select
    
    ' Perform the bisection method
    Dim low As Double, high As Double
    low = 0
    high = 0.999
    
    Dim X As Double
    Dim i As Integer
    For i = 1 To 20
        X = (low + high) / 2
        If Abs((16 * X ^ 2 * (2 - X) ^ 2) / (27 * (1 - X) ^ 4 * txtPressure.Value ^ 2) - Ke) < 0.000001 Then
            lblResult = Format(X * 100, "0.0")
            Exit Sub
        ElseIf ((16 * X ^ 2 * (2 - X) ^ 2) / (27 * (1 - X) ^ 4 * txtPressure.Value ^ 2) - Ke) > 0 Then
            high = X
        Else
            low = X
        End If
    Next i
    
    ' Display result
     lblResult = Format(X * 100, "0.0")
End Sub
Private Sub CommandButtonReset_Click()
    ' Clear the input and result controls
    txtPressure.Text = ""
    cmbTemperature.Value = ""
    lblResult = ""
End Sub
Private Sub CommandButtonQuit_Click()
    ' Close the UserForm
    Unload Me
End Sub

Now we have to create a Start button in Excel which is used to start our Conversion Calculator.



After that Press ALT+F11, Then insert a module

Copy and Paste this Code:

Sub Button1_Click()
UserForm.Show
End Sub

Now save Excel file as Excel Macro-Enabled Workbook.

Now Just Click to Click here to Start button and then Enjoy your Calculator.😏






Comments