gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
VBA excel code for BMI calculator
- User
VBA excel code for BMI calculator
- Assistant
Creating a BMI calculator using VBA in Excel involves writing a macro that calculates the Body Mass Index (BMI) based on user inputs for weight and height. Here’s a basic outline of how you can set this up:
- Open Excel and press
Alt+F11to open the VBA editor. - In the VBA editor, insert a new module by right-clicking on any of the items under "VBAProject" and selecting "Insert" > "Module".
- Paste the following VBA code into the module window:
Sub CalculateBMI() Dim ws As Worksheet Dim weight As Double Dim height As Double Dim bmi As Double Set ws = ThisWorkbook.Sheets("Sheet1") ' Adjust Sheet1 to your sheet name ' Retrieve weight and height from specific cells weight = ws.Range("A2").Value ' Assume weight in kg is in cell A2 height = ws.Range("B2").Value ' Assume height in meters is in cell B2 ' Calculate BMI If height > 0 Then bmi = weight / (height * height) ws.Range("C2").Value = Round(bmi, 2) ' Output BMI to cell C2 Else MsgBox "Height must be greater than zero." End If End Sub - Open Excel and press