Calculate Percentage in Excel VBA (Involving Macro, UDF, and UserForm)

 

Code Overview for Calculating the Percentages via VBA

Sub Calculate_Percentage()

Dim Value1 As Variant
Value1 = Range("D4").Value

Dim Value2 As Variant
Value2 = Range("C4").Value

Dim Result As Variant
Result = (Value1 / Value2) * 100

MsgBox "The Required Percentage is: " + Format(Result, "0.00") + "%"

End Sub

VBA Code to Calculate Percentage in Excel VBA


How to Calculate Percentages in Excel with VBA (Step by Step Analysis)

We’ve got a data set with the names of some products, their expected sales, and achieved sales of a company. We’ll determine the percentage of achieved sales of Full Sleeves compared to the expected sales in VBA.

Data Set to Calculate Percentage in Excel VBA

⧪ Step 1 – Declaring the Variable Whose Percentage will be Calculated

We have to declare the variable whose percentage will be calculated. We want to calculate the percentage of achieved sales of Full Sleeves. That is the value of cell D3.

Dim Value1 As Variant
Value1 = Range("D4").Value

⧪ Step 2 – Declaring the Variable with Respect to Which the Percentage will be Calculated

Ee have to declare the variable with respect to which the percentage will be calculated. Here, it’s the expected sales of Full Sleeves, the value of cell C4.

Dim Value2 As Variant
Value2 = Range("C4").Value

⧪ Step 3 – Calculating the Percentage

To calculate the percentage, divide Value1 with Value2, then multiply the result with 100.

Dim Result As Variant
Result = (Value1 / Value2) * 100

⧪ Step 4 (Optional) – Displaying the Result

You can display the result with a Message Box.

MsgBox "The Required Percentage is: " + Format(Result, "0.00") + "%"

[Here we’ve used the Format function of VBA to round the percentage to 2 decimal places.]

The complete VBA code will be:

⧭ VBA Code:

Sub Calculate_Percentage()

Dim Value1 As Variant
Value1 = Range("D4").Value

Dim Value2 As Variant
Value2 = Range("C4").Value

Dim Result As Variant
Result = (Value1 / Value2) * 100

MsgBox "The Required Percentage is: " + Format(Result, "0.00") + "%"

End Sub

VBA Code to Calculate Percentage in Excel VBA

⧭ Output:

  • Run the code by clicking the Run Sub/UserForm button in the VBA toolbar.

  • It’ll display the required percentage in a Message Box, which is 52.48%.

Output to Calculate Percentage in Excel VBA


Examples for Calculating Percentages in Excel with VBA


Example 1 – Developing a Macro to Calculate the Percentage of a Range of Cells in Excel VBA

⧭ VBA Code:

Sub Percentage_of_a_Range()

Set Range1 = Range(InputBox("The Range of Cells Whose Percentage will be Calculated: "))
Set Range2 = Range(InputBox("The Range of Cells with Respect to Which the Percentage will be Calculated: "))

Starting_Cell = InputBox("The First Cell of the Output Range: ")

Range(Starting_Cell).Cells(1, 1) = "Percentage"

Number_of_Cells_1 = Range1.Rows.Count * Range1.Columns.Count
Number_of_Cells_2 = Range2.Rows.Count * Range2.Columns.Count

If Number_of_Cells_1 <= Number_of_Cells_2 Then

    For i = 2 To Range1.Rows.Count
        For j = 1 To Range1.Columns.Count
            Range(Starting_Cell).Cells(i, j) = (Range1.Cells(i, j) / Range2.Cells(i, j)) * 100
        Next j
    Next i

Else

    For i = 2 To Range2.Rows.Count
        For j = 1 To Range2.Columns.Count
            Range(Starting_Cell).Cells(i, j) = (Range1.Cells(i, j) / Range2.Cells(i, j)) * 100
        Next j
    Next i

End If

End Sub

VBA Code to Calculate Percentage in Excel VBA

⧭ Output:

  • Run this code.
  • You’ll get 3 Input Boxes.
  • The first one will ask you to enter the range whose percentage will be calculated. Here it’s D3:D13 (Achieved Sales, including the Header).

  • The second box will ask you to enter the range with respect to which the percentage will be calculated. Here it’s C3:C13 (Expected Sales, including the Header).

Entering Inputs to Calculate Percentage in Excel VBA

  • The final box will ask you to enter the first cell of the range where the output will be stored. We’ve entered F3.

Entering Inputs to Calculate Percentage in Excel VBA

  • Click OK. You’ll get the percentages of all the achieved cells with respect to the expected cells in a range starting from F3 (With a Header of Percentage).


Example 2 – Creating a User-Defined Function to Calculate the Percentage of a Single Value or a Range of Values in Excel VBA

⧭ VBA Code:

Function PERCENTAGE(Value1, Value2)

If VarType(Value1) = 8204 And VarType(Value2) = 8204 Then

    Dim Output1() As Variant

    If Value1.Rows.Count * Value1.Columns.Count <= Value2.Rows.Count * Value2.Columns.Count Then
        ReDim Output1(Value1.Rows.Count - 1, Value1.Columns.Count - 1)
        For i = 1 To Value1.Rows.Count
            For j = 1 To Value1.Columns.Count
                Output1(i - 1, j - 1) = (Value1.Cells(i, j) / Value2.Cells(i, j)) * 100
            Next j
        Next i
        PERCENTAGE = Output1

    Else

        ReDim Output1(Value2.Rows.Count - 1, Value2.Columns.Count - 1)
        For i = 1 To Value2.Rows.Count
            For j = 1 To Value2.Columns.Count
                Output1(i - 1, j - 1) = (Value1.Cells(i, j) / Value2.Cells(i, j)) * 100
            Next j
        Next i
        PERCENTAGE = Output1

    End If

ElseIf VarType(Value1) = 8204 And VarType(Value2) <> 8204 Then

    Dim Output2() As Variant
    ReDim Output2(Value1.Rows.Count - 1, Value1.Columns.Count - 1)
    For i = 1 To Value1.Rows.Count
        For j = 1 To Value1.Columns.Count
            Output2(i - 1, j - 1) = (Value1.Cells(i, j) / Value2) * 100
        Next j
    Next i
    PERCENTAGE = Output2

Else

    Dim Output3 As Variant
    Output3 = (Value1 / Value2) * 100
    PERCENTAGE = Output3
End If     

End Function

VBA Code to Calculate Percentage in Excel VBA

⧭ Output:

  • Input 2 ranges of cells in the formula:
=PERCENTAGE(D4:D13,C4:C13)

[This is an array formula. Press Ctrl + Shift +Enter to apply it unless you use Office 365.]

  • It’ll return the percentages of the range C4:C13 with respect to the range D4:D13.

Entering Function to Calculate Percentage in Excel VBA

  • Enter a range and a single value.
=PERCENTAGE(D4:D13,500000)
  • It’ll return the percentages of the range D4:D13 with respect to 5,00,000.

  • Enter two single values.
=PERCENTAGE(180000,343000)
  • It’ll return the percentage of 180,000 with respect to 343,000.

Entering Function to Calculate Percentage in Excel VBA


Example 3 – Developing a UserForm to Calculate the Percentage of a Single Value or a Range of Values in Excel

⧪ Step 1 – Inserting the UserForm

  • Go to the Insert tab and select the UserForm option in the VBA toolbar to insert a new UserForm.

Inserting UserForm to Calculate Percentage in Excel VBA

⧪ Step 2: Dragging Tools to the UserForm

  • A UserForm called UserForm1 will open, along with a Toolbox called Control.
  • Move your mouse over the Toolbox and drag a ListBox (ListBox1) to the top-left corner of the UserForm.
  • Drag 5 Labels (Label1, Label2, Label3, Label4, and Label5) and 5 TextBoxes (TextBox1, TextBox2, TextBox3, TextBox4, and TextBox5).
  • Drag a CommandButton (CommandButton1) to the bottom-right corner.
  • Change the displays of the Labels to Value, With Respect to, Range, With Respect to, and Output Location (First Cell) respectively.
  • Change the display of the CommandButton1 to OK.

⧪ Step 3 – Writing Code for ListBox1

  • Double-click on ListBox1.
  • A Private Subprocedure called ListBox1_Click will open.
  • Enter the following code there.
Private Sub ListBox1_Click()

If UserForm1.ListBox1.Selected(0) = True Then

    UserForm1.Label1.Visible = True
    UserForm1.Label2.Visible = True

    UserForm1.Label3.Visible = False
    UserForm1.Label4.Visible = False
    UserForm1.Label5.Visible = False

    UserForm1.TextBox1.Visible = True
    UserForm1.TextBox2.Visible = True

    UserForm1.TextBox3.Visible = False
    UserForm1.TextBox4.Visible = False
    UserForm1.TextBox5.Visible = False

ElseIf UserForm1.ListBox1.Selected(1) = True Then

    UserForm1.Label1.Visible = False
    UserForm1.Label2.Visible = False

    UserForm1.Label3.Visible = True
    UserForm1.Label4.Visible = True
    UserForm1.Label5.Visible = True

    UserForm1.TextBox1.Visible = False
    UserForm1.TextBox2.Visible = False

    UserForm1.TextBox3.Visible = True
    UserForm1.TextBox4.Visible = True
    UserForm1.TextBox5.Visible = True

End If

End Sub

VBA Code to Calculate Percentage in Excel VBA

⧪ Step 4 – Writing Code for TextBox3

  • Double-click on TextBox3.
  • Another Private Subprocedure called TextBox3_Change will open.
  • Enter the following code there.
Private Sub TextBox3_Change()

On Error GoTo Message

Range(UserForm1.TextBox3.Text).Select

Message:
    X = 240

End Sub

TextBox3 Code to Calculate Percentage in Excel VBA

⧪ Step 5 – Writing Code for TextBox4

  • Double-click on TextBox4.
  • When the Private Subprocedure called TextBox4_Change opens, enter this code there.
Private Sub TextBox4_Change()

On Error GoTo Message
  
Range(UserForm1.TextBox4.Text).Select

Message:
    X = 240

End Sub

⧪ Step 6 – Writing Code for TextBox5

  • Double-click on TextBox5.
  • After the Private Subprocedure called TextBox5_Change opens, insert the following code there.

Private Sub TextBox5_Change()

On Error GoTo Message

Range(UserForm1.TextBox5.Text).Select

Message:
    X = 240

End Sub

TextBox5 Code to Calculate Percentage in Excel VBA

⧪ Step 7 – Writing Code for CommandButton1

  • Double-click on the CommandButton1 (displayed as OK).
  • A Private Subprocedure called CommandButton1_Click will open.
  • Enter the following code there.
Private Sub CommandButton1_Click()

If UserForm1.ListBox1.Selected(0) = True Then
    On Error GoTo Message1
    Result = (UserForm1.TextBox1.Text / UserForm1.TextBox2.Text) * 100
    MsgBox "The Required Percentage is: " + Format(Result, "0.00") + "%"

ElseIf UserForm1.ListBox1.Selected(1) = True Then

    On Error GoTo Message2

    Set Range1 = Range(UserForm1.TextBox3.Text)
    Set Range2 = Range(UserForm1.TextBox4.Text)

    Starting_Cell = UserForm1.TextBox5.Text

    Range(Starting_Cell).Cells(1, 1) = "Percentage"

    Number_of_Cells_1 = Range1.Rows.Count * Range1.Columns.Count
    Number_of_Cells_2 = Range2.Rows.Count * Range2.Columns.Count

    If Number_of_Cells_1 <= Number_of_Cells_2 Then
        For i = 2 To Range1.Rows.Count
            For j = 1 To Range1.Columns.Count
                Range(Starting_Cell).Cells(i, j) = (Range1.Cells(i, j) / Range2.Cells(i, j)) * 100
            Next j
        Next i

    Else
        For i = 2 To Range2.Rows.Count
            For j = 1 To Range2.Columns.Count
                Range(Starting_Cell).Cells(i, j) = (Range1.Cells(i, j) / Range2.Cells(i, j)) * 100
            Next j
        Next i
    End If

Else

    MsgBox "Select one between Single Value or Range of Cells.", vbExclamation

End If

Exit Sub

Message1:
    MsgBox "Enter Valid Numbers for the Values.", vbExclamation

Exit Sub

Message2:
    MsgBox "Enter Valid Range of Cells for the Ranges.", vbExclamation

End Sub

⧪ Step 8 – Code for Running the UserForm

  • Insert a new Module from the VBA toolbar and insert the following code.
Sub Run_UserForm()

UserForm1.Caption = "Percantage with VBA"

UserForm1.TextBox3.Text = Selection.Address

UserForm1.ListBox1.AddItem "Single Value"
UserForm1.ListBox1.AddItem "Range of Cells"

UserForm1.ListBox1.ListStyle = fmListStyleOption
UserForm1.ListBox1.BorderStyle = fmBorderStyleSingle

UserForm1.Label1.Visible = False
UserForm1.Label2.Visible = False
UserForm1.Label3.Visible = False
UserForm1.Label4.Visible = False
UserForm1.Label5.Visible = False

UserForm1.TextBox1.Visible = False
UserForm1.TextBox2.Visible = False
UserForm1.TextBox3.Visible = False
UserForm1.TextBox4.Visible = False
UserForm1.TextBox5.Visible = False

Load UserForm1
UserForm1.Show

End Sub

VBA Code to Calculate Percentage in Excel VBA

⧪ Step 9 – Running the UserForm

  • Run the Macro called Run_UserForm.

Running Macro to Calculate Percentage in Excel VBA

  • The UserForm will load with the name Percentage with VBA.
  • Select Single Value or Range of Values.

  • If you select Single Value, 2 TextBoxes will appear. Enter the value whose percentage you want to calculate and the value with respect to which to calculate. I’ve entered 46 and 205.

UserForm to Calculate Percentage in Excel VBA

  • Click OK.
  • A Message Box will display the required percentage.

Output to to Calculate Percentage in Excel VBA

  • If you select Range of Cells, three TextBoxes will appear asking you to input the range whose percentage you want to calculate, the range with respect to which to calculate, and the first cell of the output location. We’ve entered D3:D13, C3:C13 (with Headers), and F3.

  • Click OK.
  • You’ll find the required percentages in a range starting from F3 (with a Header called Percentage).


Download the Practice Workbook


Related Articles


<<Go Back to Calculating Percentages in Excel | How to Calculate in Excel | Learn Excel

Get FREE Advanced Excel Exercises with Solutions!
Rifat Hassan
Rifat Hassan

Rifat Hassan, BSc, Electrical and Electronic Engineering, Bangladesh University of Engineering and Technology, has worked with the ExcelDemy project for almost 2 years. Within these 2 years, he has written over 250 articles. He has also conducted a few Boot Camp sessions on effective coding, especially Visual Basic for Applications (VBA). Currently, he is working as a Software Developer to develop and deploy additional add-ins to enhance the customers with a more sophisticated experience with Microsoft Office Suits,... Read Full Bio

5 Comments
  1. Hello..!! Iam sending auto mulitple mails weekly of performance where i need to show percentage to them on mail body.. Percentage should reflect soon the pivot will get refresh..So request can you pls advice with the vba script for same ..

    • Hello Tushar Chauhan,
      Thanks for reaching us. According to your stated scenario, I have created the following dataset for some imaginary employees. Using their weekly presence and targeted presence we will calculate their weekly percentages here.
      1
      In the process of creating PivotTable, make sure to check the Add this data to the Data Model option.
      2
      • Drag down the SalesPerson and Email Id fields to the Rows area and Weekly Presence and Targeted Presence fields to the Values area.
      3
      • To add a new measure for calculating percentages right-click on the table name Range and select the Add Measure option.
      4
      • In the Measure dialog box, enter Percentage as Measure Name and use the following formula in the Formula box
      =[Sum of Weekly Presence]/[Sum of Targeted Presence]
      5
      • Choose Number as Category and then select the Percentage option.
      • Press OK.
      6
      • Drag down the newly created Percentage measure to the Values area.
      7
      Afterward, you will get the Percentage column in your PivotTable.
      8
      Now, if you change any data of your main dataset then the values of the PivotTable will be updated also.
      For instance, we have changed the values of the Weekly Presence column in the main dataset.
      9
      • Now go to the sheet with PivotTable and then go to the PivotTable Analyze tab >> Refresh group >> Refresh option.
      10
      After that, the percentages will be updated also.
      11
      To send these percentages to individual employees automatically using VBA script you can follow this article https://www.exceldemy.com/send-bulk-email-from-outlook-using-excel/
      After going through this article, you will notice different ways of doing this task.

  2. Hello.. iam using this code but getting error 6 : Overflow.. Can you pls help on same to work on the code..

  3. Hello Tanjima…

    Thank you so much for helping me out..

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo