Open In App

How to Create Dynamic Range Based on Cell Value in Excel VBA?

Last Updated: 11 Mar, 2023

R

Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Dynamic ranges in excel VBA provide us with the flexibility to define ranges beyond the specific values. The dynamic range enables the program to perform transformation and data management steps with ease without the worry of changing the range of the data set. The dynamic range in excel VBA promotes code reusability and does not make the programming logic to be redundant. By utilizing the range object and cells object, the dynamic ranges in Excel VBA can be defined and created. There are many ways in which dynamic ranges can be created. Following are the methods listed below:

  • Variable initialization to the range and cell object.
  • Create a Dynamic range passed as the value in another excel cell.

The following examples help in illustrating the above methods,

Variable Initialization to Range and Cell Object

With the change in the size of the data, it would be useful if the range object that is used to refer to the ranges can be modified. The following code helps in counting the last row and column in an excel as shown below

Sub test()

Dim EndR As Integer

Dim lastCl1 As Integer

Sheet2.Activate

EndR = Sheet2.Range(“A1”).End(xlUp).Row

lastCl1 = Sheet2.Range(“XFD1”).End(xlToLeft).Column

MsgBox EndR

MsgBox lastCl1

End Sub

The above code can be used along with the combination of range and cell object to create a dynamic range. Following is the code for Dynamic range as shown below

Sub test()

Dim EndR As Integer

Dim lastCl1 As Integer

Sheet2.Activate

EndR = Sheet2.Range(“A1048576”).End(xlUp).Row

lastCl1 = Sheet2.Range(“XFD” & EndR).End(xlToLeft).Column

MsgBox EndR

MsgBox lastCl1

Set DynamicRange = Sheet2.Range(Cells(1, 1), Cells(EndR, lastCl1))

MsgBox “Range is ” & DynamicRange.Address

End Sub

Code:

Code-for-dynamic-range

 

When the above code is executed in the VBA, following is the result:

result-of-code-execution

 

Create a Dynamic Range Passed as Value in Another Excel Cell

Let us take another example where we take the below data set and select multiple rows for the below data set, we have an empty cell value to assign the ranges with the value 

dataset

 

let us assign the range value as 3. The below VBA codes take a value from the active sheet and assign it to the range object to create a dynamic range. 

Sub test2()

Dim EndR As Variant

Sheet2.Activate

EndR = Sheet2.Range(“E3”).Value

Set DynamicRange = Sheet2.Range(“A1:B” & EndR)

DynamicRange.Select

End Sub

Code:

Code-for-dynamic-range

 

Following would be the output as shown below,

range-value-obtained

 

Let us take another example where we take the below data set and select multiple rows for the below data set using two cell values instead of one cell, we have an empty cell value to assign the ranges with the value.

column-value-assigned

 

Let us assign the range value as Starting range as A1 and the ending range as B4. The below VBA codes take a value from the active sheet and assign it to the range object to create a dynamic range.

Sub test2()

Dim EndR As Variant

Dim Endcl As Variant

Sheet2.Activate

EndR = Sheet2.Range(“E3”).Value

Endcl = Sheet2.Range(“E4”).Value

Set DynamicRange = Sheet2.Range(EndR & “:” & Endcl)

DynamicRange.Select

End Sub

Code:

VBA-code

 

Following would be the output as shown below,

value-assigned-to-range-object

 

Summary

  • The above codes help in understanding how to create a dynamic range in VBA.
  • Dynamic range helps in boosting code reusability and helps in effective data management.


R

News
Improve
Discuss
Do you want to advertise with us?Click here to know more

VBA Subroutine in Excel - How to Call Sub in VBA?

article_img
When a specified action is performed on a worksheet with the help of a collection of code known as a VBA Subroutine. It also helps to read an external file, also it can open other applications from Excel. A large piece of code can be broken into small parts so that we can manage it easily. Let's learn why to use submarines: Converts large piece of codes into small parts so that the computer ignores all kind of complexities that arises because of large codesReusability of code suppose we in a program have to access the database frequently so instead of writing the code again and again we can create a function to access the databaseSubroutines are self-documenting functions which means a coder can easily say what the program does by looking into the name of the function Naming Rules of SubroutinesIt can start with a letter or an underscore but it cannot start with a number or a special character.It cannot contain any space in the name.The name of the subroutine cannot be a keyword like Private, Sub, End, etc. Syntax Private Sub function_name( ByVal arg1 As String, ByVal arg2 As String) End Sub Syntax Explanation Code Action "Private Sub function_name(...)"Private is the keyword whic
Read More

How to Set Variable to Cell Value in Excel VBA?

article_img
Adding data to the worksheet is often done and it is essential to learn how to set variable to cell value in excel VBA. There can be instances when you want to add the same data to your worksheet. This task could easily be achieved with the help of Excel VBA variables. You can assign your cell values with variables. Let's learn how to set variables to cell values in Excel VBA. Declaring Variables in VBA Before learning the assignment of variables, one needs to know what are variables and why they are used? Like any other programming language, VBA has variables. Variables are the containers to store data in them. There are some rules for storing data in them. Rules for naming Variables The variable name cannot start with a number.While naming the variables you cannot have space between the names which means a space character (' ') is prohibited.The length of the variable name should be less than Two-hundred and fifty-five (255) characters. Implicit and Explicit Declaration In Excel VBA, variables can be classified into 2 categories implicit and explicit, Implicit Declaration The implicit declaration declares a variable of data type variant. When we create variables implicitly, we ne
Read More

Get, Set, or Change Cell value in Excel VBA

article_img
VBA, or Visual Basic for Applications, is a programming language developed by Microsoft. It is used to automate repetitive tasks, enhance functionality, and create custom solutions within Microsoft Office applications like Excel, Word, and Access. VBA allows users to write scripts or small programs to perform tasks such as data manipulation, complex calculations, and generating reports, making work more efficient and customized to specific needs. We use VBA to automate our tasks in Excel. The idea of using VBA is to connect the interface of Excel with the programming. One of the very most important connections between them is by changing the cell values. The change in cell value by programming shows the power of VBA. In this article, we will see how to set, get, and change the cell value.  Get, Set, or Change Cell value in Excel VBAHow to Set Cell Value in Excel VBAAssigning a cell with a value can be achieved by very two famous functions in VBA i.e. Range and Cells function.  Range Function in VBAThe range function helps access the cells in the worksheet. To set the cell value using the range function, we use the .Value.  Syntax: Range(cell_name).Value = value_to_be_assinged. 1. S
Read More

Trapping Dynamic Ranges in Excel VBA

article_img
Dynamic Ranges give the flexibility to work with more range of cells as compared to a specific range of cells which usually limits us to work with a particular range of cells. As the size of the data may change in an excel sheet so it is also necessary to change the range in the code dynamically for that dynamic ranges are used. We can trap dynamic ranges in different ways: Last Row in ColumnLast Column in Row Special cells Used RangeCurrent RegionNamed Region TablesLast Row in Column This is used to get the number of the last row in the column by using two methods i.e Range() and End(). Range("x1048576") is the syntax where x represents the name of the cell for which we are trapping the last row and 1048576 is the total number of rows in the sheet. End(Direction as xlDirection) where we are searching for the last row we will mention xlUp to go in the last row of the worksheet. The following code is written to get the number of the last row in cell "C" Last Column in Row This is used to get the number of the last column in the row by using two methods i.e Range() and End(). Range("XFDz") is the syntax where XFD is the last column of the worksheet and z represents the number of the
Read More

Generating Dynamic Charts With VBA in Excel

article_img
A powerful graph range is an information range that refreshes naturally when you change the information source. This unique reach is then utilized as the source information in an outline. As the information changes, the powerful reach refreshes right away which prompts an update in the outline. The following is an illustration of a graph that utilizes a unique outline range. Sample Data Follow the further steps in Generating Dynamic Charts with VBA in Excel Step 1: Opening the Visual Essential Window. Press ALT+F11 on your console to open the Visual Essential Window. Step 2: Embedding Another Module. Go to the Addition > Module choice in the toolbar. Click on Module. Another module called Module1 will be embedded. Step 3: Putting the VBA Code sub create _dynamic_ chart () Application . ScreenUpadting = False with Activesheet. shapes ( Application .caller ) .Fill.Forecolor If . Brightnesss = 0 Then . Brightness = -0.150000006 Else . Brightness = 0 End If End With Dim Sequence ( ) As String Desired__shapes = Array ( " Rounded Rectangle 1" , " Rounded Rectangle 2 " , " Rounded Rectangle For i = LBound ( Desired _Sh
Read More

How to Create a User Defined Function in Excel VBA

article_img
A function is a collection of code.  As a developer, we very often need a custom function (User-defined function) in our projects. These functions can be used as normal functions in Excel. These are helpful when the existing functions are not enough. In such cases, the user can create his own custom user-defined function to fulfil the need.  What are User Defined FunctionsUser Defined Function(UDF) is the custom function that is created by the user to perform a specific task in VBA(Virtual basic application) which is a programming language in Excel. Function Vs. Subroutine in VBA In VBA, a 'Subroutine' lets you run a group of commands, while a 'Function' provides a result. For example, consider a list of numbers, some positive and some negative. With a subroutine, you can scan each cell and mark negative ones by changing their colour. The subroutine modifies the cell properties. On the other hand, a custom function can be used in a separate column. It returns TRUE for negative values and FALSE for positive ones. Functions can't change cell properties directly but can be used with conditional formatting for the same effect. When you create a User Defined Function (UDF) in VBA, you c
Read More

How to Create Charts in Excel Using Worksheet Data and VBA?

article_img
Excel is an important software provided by Microsoft Corporation. This software belongs to one of the major software suites Office 365. In this software suite, there are other software are present like Word, PowerPoint, etc. They are called Office 365, as this software are mostly used for office purpose. But now the world has changed a lot. After the Corona Pandemic, the world knows the positivity of using digital tools. Office 365 was not different from that. As a part of the software suite, Excel software also gains some importance from the users. They are not only used for official purposes. But they can also be used for school purposes. Excel is software that can able to store data in an effective form. So, searching for the data becomes more manageable in this software. Excel has another great feature. It can be used to derive the charts from the provided data. The charts are helpful for analyzing any growth of the data. If there are thousands of data present, it is a difficult task to extract some analysis from that data. But if those data are converted to charts, then it will be easy to analyze those data. Excel sheet helps to do the same. Charts can be prepared whatever the
Read More

How to Create an Input Box With Multiple Inputs in Excel Using VBA?

article_img
The Input Box is a dialogue box that helps users to take a value and do later computations according to the entered value. The input box is similar to the message box, but the message box is used to display the data while the input box is used to enter the data. By default, a message box displays only the Ok button in its conversation box, whereas an input box displays both the Ok and Cancel buttons. You can specify the type of data to be returned. In excel VBA Macro, Input Box is one of the most commonly used functions. In this example, we will learn how to create an input box using excel VBA which consumes multiple data from the end-user. For this, we will be creating a user form. Step By Step Implementation Step 1: Insert Visual Basic Editor To insert Visual Basic Editor in excel please refer to How to Insert and Run VBA Code in Excel? Step 2: Insert User Form In this step, we need to add a user form to our VBA. For this, we need to go to the Developer tab on the top of the ribbon and then select Visual Basic. Fig 1 - Open Visual Basic Once we click on the Visual Basic option, excel will open Visual Basic Editor in a new window. Fig 2 - Visual Basic Editor In the Visual Basic Ed
Read More

Highlight Rows Based on a Cell Value in Excel

article_img
Conditional formatting is a game-changer when it comes to making large data sets in Excel more readable and actionable. If you've ever wanted to draw attention to rows that meet specific criteria—whether it's identifying underperforming metrics, blank entries, or matching specific text values—learning how to highlight rows in Excel is an essential skill. This article breaks down the step-by-step process, covering everything from formatting rows based on text or numeric values to applying multiple conditions with different colors. With these techniques, you can elevate your Excel sheets into powerful tools for visual data analysis.Highlight Rows Based on a Cell Value in ExcelTable of ContentReal-World Example: Highlighting Rows in Employee Data How to Highlight Rows Based on a Cell Value 1. Highlight Rows Based on Text Match 2. Highlight Rows Based on Numeric Values 3. Highlight Rows Using OR/AND Conditions4. Highlight Rows with Blank Cells 5. Highlight Rows Based on Multiple Conditions with Different Colors Why Highlight Rows Based on a Cell ValueHighlighting rows based on a cell value offers the following benefits:Improved Data Analysis: Quickly locate important rows in large data
Read More

How to Use Select Case Statement in Excel VBA?

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. In this article, we are going to discuss how to use Select Case Statement in Excel VBA. Select Case Statement of Excel VBA The select case in VBA is like a detective that investigates an expression by checking it against different scenarios listed as Case Statements, each with its own conditions. When a scenario matches the expression, it's like solving a piece of the puzzle, and the corresponding code linked to that scenario is activated. Importantly, once a match is found, the detective stops investigating and moves on to executing the discovered code. Yet, if none of the scenarios match, it's like the detective hitting a dead end. In this situation, the code associated with the Case Else statement comes into play, offering a default solution or outcome. Syntax of the Select Case Statement of Excel VBAThe VBA Select Case Statement shares similarities with the Switch Case construct found in programming languages such as Java, C#, and PHP. In Excel VBA, this statement helps
Read More
three90RightbarBannerImg