Lesson#195: How to make a Basic calculator in VBA

Lesson#195: How to make a Basic calculator in VBA

To create a calculator in Microsoft Excel using Visual Basic for Applications (VBA), you can follow these steps:

  1. Open a new blank Excel spreadsheet.
  2. Select the “Developer” tab in the ribbon. If the Developer tab is not visible, you can enable it by going to the “File” tab and selecting “Options” from the menu. In the “Excel Options” window, select the “Customize Ribbon” tab and check the “Developer” box in the “Main Tabs” list.
  3. Click the “Insert” button in the “Controls” group of the Developer tab, and then select “Button” from the list of controls.
  4. Click and drag on the spreadsheet to draw the button.
  5. Right-click the button and select “View Code” from the menu. This will open the VBA editor with a blank event handler for the button’s “Click” event.
  6. Type the following code in the event handler:
Private Sub CommandButton1_Click()

Dim num1 As Double
Dim num2 As Double
Dim result As Double

num1 = InputBox("Enter the first number:")
num2 = InputBox("Enter the second number:")

result = num1 + num2

MsgBox "The result is: " & result

End Sub

This code will prompt the user to enter two numbers, add them together, and display the result in a message box.

  1. Repeat steps 3-6 for each operation (e.g., addition, subtraction, multiplication, division) that you want to include in the calculator. You will need to modify the code in the event handler to perform the appropriate operation based on the button that was clicked.
  2. To display the result of the calculation, you can create a label control and set its text property to the value of the “result” variable. You can also create a text box control and use it to display the current value of the “result” variable, allowing the user to enter additional calculations using the result as the starting value.
See also  Lesson#179: Count cells by color in Excel from a reference cell color with VBA

Hi! I am Puspendu. I am the founder and author of Excelabcd. I am little creative person, blogger and Excel-maniac guy. I hope you enjoy my blog.

Leave a Reply

Your email address will not be published. Required fields are marked *

*