Insert VBA Code

In this article, we will learn how we can enter the VBA code in Microsoft Excel.

While entering the VBA code, we need to follow the below procedure:-

  • A Comment (this line start with apostrophe)
  • A Variable declaration statement (this line start with DIM)
  • Two Variables (Total and i)
  • Two assignments (Total = 0 and Total = Total + i)
  • Loop structure (For-Next)
  • A VBA function (MsgBox)

Now, we will understand with writing the code, the following example combines four instructions on one line:-

VBA code, located in a VBA module, contains instructions. The recognized practice is needed to use one instruction per line. This standard isn’t a requirement. To separate multiple instructions, we will use Colon on a single line.

Sub OneLine()
X = 34: y = 21: z = 22: MsgBox x + y + z
End Sub

image 1

  • Press F5 to run the macro
  • You will get the Msgbox with calculation results

image 2

If you want to make it easier to read, follow below mentioned VBA code: –

Sub OneLine()
X = 34
y = 21
z = 22
MsgBox x + y + z
End Sub

image 3

  • Press F5 to run the code
  • You will get the calculated Msgbox

Sub LongLine()
ActiveCell = Worksheets(“sheet1”).Range(“A1”).Value + Worksheets(“Sheet2”).Range(“A1”).Value
End Sub

image 4

  • Press F5 to run the code
  • In cell A3, you get the sum of cells A1 from both sheets

Previous Chapter Next Chapter

Leave a Reply