tag:blogger.com,1999:blog-28701181272450117002024-03-18T20:08:14.316-07:00Excel-VBA SolutionsWant to become an expert in VBA? So this is the right place for you. This blog mainly focus on teaching how to apply Visual Basic for Microsoft Excel. So improve the functionality of your excel workbooks with the aid of this blog. Also ask any questions you have regarding MS Excel and applying VBA. We are happy to assist you.Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.comBlogger222125tag:blogger.com,1999:blog-2870118127245011700.post-31524831565123333052024-02-11T19:21:00.000-08:002024-02-20T18:35:16.426-08:00Select Method of Range Class Failed Error in VBA <script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In the Excel VBA development, encountering errors can be a common yet frustrating experience. A frequent issue that specially new developers encounter is the "Select Method of Range Class Failed" error. This article aims to unveil this error, offering insights into its cause and presenting a solution to resolve it.
</p>
<div class="table-of-contents" style="text-decoration:none;">
<b>Table of contents</b><br>
<a href="#select_method_err_insight">Understanding the "Select Method of Range Class Failed" Error</a><br>
<a href="#select_method_err_cause">Cause of the Error</a><br>
<a href="#select_method_err_fix">How to Fix the Error</a>
</div>
<br><br>
<h4 id="select_method_err_insight">Understanding the "Select Method of Range Class Failed" Error</h4>
<p>
The "Select Method of Range Class Failed" error typically arises when VBA code attempts to select a range that is inaccessible at the time of the code execution.</p>
<h4 id="select_method_err_cause">Cause of the "Select Method of Range Class Failed" Error</h4>
<p>
Understanding the underlying cause is critical to resolving the error. Below is the reason for this error.
</p>
<p>
<b>Inactive Worksheet</b><br>
Trying to select a range on a worksheet that is not currently active can lead to this error. Let’s consider this example Excel workbook.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjaXu6K2x4ja_BZvsZ48yoENaNEP5s_YUJ4e5g4YuMjEd-Mnvo6K8dpFopKzZBWzvjif8Yc6QCjaNh-2JQIzuK83jz6ek-AOZKgkMUl0NhCoSxu_aWPg-dy9g5Zp6OjFzhNz62GMHjfAZNGd4IxUi3HLP_PQM-5XkghHiNB4VIyFdSYF_Cp6O3hACpXPrc/s1600/Img%201%20-%20Example%20workbook.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Example workbook" border="0" data-original-height="457" data-original-width="595" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjaXu6K2x4ja_BZvsZ48yoENaNEP5s_YUJ4e5g4YuMjEd-Mnvo6K8dpFopKzZBWzvjif8Yc6QCjaNh-2JQIzuK83jz6ek-AOZKgkMUl0NhCoSxu_aWPg-dy9g5Zp6OjFzhNz62GMHjfAZNGd4IxUi3HLP_PQM-5XkghHiNB4VIyFdSYF_Cp6O3hACpXPrc/s1600/Img%201%20-%20Example%20workbook.png"/></a></div>
<p>
This Excel file contains two worksheets. “Input” and “Output” sheets. Currently we are in the “Input” sheet. So the “Input” sheet is the worksheet active at the moment. Assume we tried to select the A1 cell of the “Output” now using the below subroutine.
</p>
<div class="vba-code-block">
Sub InactiveWorksheetExample()<br><br>
Dim WS_Input As Worksheet<br>
Dim WS_Output As Worksheet<br><br>
Set WS_Input = Worksheets("Input")<br>
Set WS_Output = Worksheets("Output")<br><br>
WS_Output.Range("A1").Select<br><br>
End Sub
</div>
<p>
Here what we are doing is we are asking the macro to select a cell from a worksheet which is not active. So this will throw the following error - Run-time error '1004' - Select method of Range class failed.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhe0Maug2_DnuR2ioWaJ8-CeK3YZDq7WJBC8tRyUMVFkmudkqkvVTThsPLpZ0JRi14KFEhXedJidECqeX67XcCxYoWDQdF_1NyVp7f_ouEcekkx_REiDIRJHln3seLjVWLE8qWBQaev9UynQ0izf6F8zW8h8VS4eICd4WQz65jKbRQJsmJ2JaELwceUAkA/s1600/Img%202%20-%20Select%20Method%20of%20Range%20Class%20Failed%20Error.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select Method of Range Class Failed Error" border="0" data-original-height="257" data-original-width="434" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhe0Maug2_DnuR2ioWaJ8-CeK3YZDq7WJBC8tRyUMVFkmudkqkvVTThsPLpZ0JRi14KFEhXedJidECqeX67XcCxYoWDQdF_1NyVp7f_ouEcekkx_REiDIRJHln3seLjVWLE8qWBQaev9UynQ0izf6F8zW8h8VS4eICd4WQz65jKbRQJsmJ2JaELwceUAkA/s1600/Img%202%20-%20Select%20Method%20of%20Range%20Class%20Failed%20Error.png"/></a></div>
<br><br>
<h4 id="select_method_err_fix">How to Fix the Error</h4>
<p>
To tackle this error, we can simply activate the required sheet. So before selecting a range, make sure the relevant sheet is activated using Worksheet.Activate method. Here is how you can modify the above subroutine to do that.
</p>
<div class="vba-code-block">
Sub InactiveWorksheetExample()<br><br>
Dim WS_Input As Worksheet<br>
Dim WS_Output As Worksheet<br><br>
Set WS_Input = Worksheets("Input")<br>
Set WS_Output = Worksheets("Output")<br><br>
WS_Output.Activate<br>
WS_Output.Range("A1").Select<br><br>
End Sub
</div>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-81681379230188622832024-02-06T19:21:00.000-08:002024-02-06T19:21:03.862-08:00Method 'Range' of object '_Worksheet' Failed Error in VBA<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
When working with VBA in Excel, encountering errors is not uncommon, especially when dealing with range objects. One such error is the "Method 'Range' of object '_Worksheet' failed". In this post we will explore the causes of this VBA error and how to effectively troubleshoot and resolve it.
</p>
<div class="table-of-contents" style="text-decoration:none;">
<b>Table of contents</b><br>
<a href="#method_range_error_intro">Introduction to Method 'Range' of object '_Worksheet' Failed Error</a><br>
<a href="#method_range_error_common_causes">Common Causes of the VBA Error</a><br>
<a href="#method_range_error_troubleshooting">Troubleshooting the Error</a>
</div>
<br><br>
<h4 id="method_range_error_intro">Introduction to Method 'Range' of object '_Worksheet' Failed Error</h4>
<p>
The "Method 'Range' of object '_Worksheet' failed" error in VBA typically occurs when the code tries to reference a range that does not exist or is incorrectly specified. This error can be frustrating, especially for those new to VBA. Understanding the nature of this error is the first step in resolving it.
</p>
<h4 id="method_range_error_common_causes">Common Causes of the Range Method Error</h4>
<!-- Several factors can lead to this error -->
<p>
<b>Incorrect Range Reference</b><br>
When the specified range in the code does not exist in the worksheet. Here is a simple example.
</p>
<div class="vba-code-block">
Sub SelectRange()<br><br>
Dim WS As Worksheet<br><br>
Set WS = ActiveSheet<br><br>
WS.Range("B1400000").Select<br><br>
End Sub
</div>
<p>
In this example, macro is trying to select a cell called B1400000. But such a cell is not available in Excel because the row limit of the Excel application is 1,048,576.
</p>
<p>
Check this post to see more details about Excel row limit.<br>
<a href="https://www.excelvbasolutions.com/2014/05/number-of-rows-in-excel-2013.html">Number of rows in Excel</a>
</p>
<p>
So when we run the macro it will show this error message.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0xYs_ZmZO4wEEvb9owiaq8qxJcig3Tv9bbhURZQUAICIyDicBWdgawh_gyp3iZTlB5PWOWC04UWS4Lg4MLJFcbYHU2OR4Cki7Zeyj3RJCTEJLLP8QlICiQ_8VUqHP5ubxtK9EYYXM8qCheU0i4t3ilz3WqRv9XSncKKI5X2F2nekGdukMGLGy0ddz8h0/s1600/Img%201%20-%20Method%20%27Range%27%20of%20object%20%27_Worksheet%27%20Failed%20Error.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Method 'Range' of object '_Worksheet' Failed Error" border="0" data-original-height="253" data-original-width="430" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0xYs_ZmZO4wEEvb9owiaq8qxJcig3Tv9bbhURZQUAICIyDicBWdgawh_gyp3iZTlB5PWOWC04UWS4Lg4MLJFcbYHU2OR4Cki7Zeyj3RJCTEJLLP8QlICiQ_8VUqHP5ubxtK9EYYXM8qCheU0i4t3ilz3WqRv9XSncKKI5X2F2nekGdukMGLGy0ddz8h0/s1600/Img%201%20-%20Method%20%27Range%27%20of%20object%20%27_Worksheet%27%20Failed%20Error.png"/></a></div>
<br>
<h4 id="method_range_error_troubleshooting">Troubleshooting the Range Method Error</h4>
<p>
To troubleshoot this error, follow these steps.
</p>
<p>
<b>Check Range References</b><br>
Ensure that the range referenced in the code exists in the worksheet.
</p>
<p>
<b>Debugging</b><br>
Use VBA's debugging tools, like the Immediate Window and Local Window, to track the values and state of variables at runtime. If your code is referencing dynamic ranges then you can detect whether it is referencing nonexistent ranges.
</p>
<p>
<b>Error Handling</b><br>
Implement error-handling routines to catch and handle errors.
</p>
<p>
The error "Method 'Range' of object '_Worksheet' failed" can be a hurdle in VBA programming, but with careful examination of the code, validation of references, and implementation of best practices, it can be effectively managed and resolved. Understanding the root causes and having a structured approach to troubleshooting are key to overcoming this challenge in Excel VBA.
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-47637521607469463082024-01-22T09:27:00.000-08:002024-01-22T09:33:51.700-08:00How to Get Selected Item from VBA Listbox<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In this lesson, we will explore how to extract the selected value from a multicolumn listbox using VBA in Excel. This is particularly useful when you have a listbox filled with multiple columns of data and you need to retrieve specific values based on user interaction. The process may seem complex, but with the right approach, it becomes a straightforward task.
</p>
<div class="table-of-contents" style="text-decoration:none;">
<b>Table of contents</b><br>
<a href="#listindex_property">Using the ListIndex Property</a><br>
<a href="#extracting_value_using_list_property">Extracting Value from a Specific Column of the Selected Row - Using List Property</a><br>
<a href="#handling_multiple_selections">Handling Multiple Selections For MultiSelect Enabled ListBoxes</a><br>
<a href="#extracting_selected_values_using_column_property">Extracting Selected Value from a Listbox - Using Column Property</a><br>
<a href="#tips_and_tricks_get_selected_item_vba_listbox">Tips and Tricks for Effective Coding</a>
</div>
<p>
Before diving into extracting values, it's crucial to understand what a listbox is. Essentially, it's a VBA control that can display items across multiple columns, like a simple table or spreadsheet. This functionality is very useful when you need to show more than one attribute of an item in a VBA control. Because in other VBA controls such as text boxes you can only show one attribute. So the VBA listboxes enhance the user experience by allowing users to view and select from a range of related data points.
</p>
<p>
Now let’s look at how we can get selected items from a VBA listbox in a few different ways.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6crvcpm6kJxOyq9Gc4CqAeHXIbyXXh4yHWblJMr34FjrhW9liBeFlQs7L9YaMgXW59MkMuq0kX-53e28U49TlcQFdv4GisrerO-DLoWqc01UsZSA5iP0rJUgwbHbcBbvN8amexH7c87hto0ZbU8i5XnN-QVOqmWkAWyTBqYLI58J1uLK9cLjXLF-_nBs/s1600/Img%201%20-%20Sample%20Excel%20sheet%20to%20show%20how%20to%20get%20selected%20item%20from%20a%20listbox.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample Excel sheet to demonstrate how to get selected item from a listbox" border="0" data-original-height="719" data-original-width="1024" width ="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6crvcpm6kJxOyq9Gc4CqAeHXIbyXXh4yHWblJMr34FjrhW9liBeFlQs7L9YaMgXW59MkMuq0kX-53e28U49TlcQFdv4GisrerO-DLoWqc01UsZSA5iP0rJUgwbHbcBbvN8amexH7c87hto0ZbU8i5XnN-QVOqmWkAWyTBqYLI58J1uLK9cLjXLF-_nBs/s1600/Img%201%20-%20Sample%20Excel%20sheet%20to%20show%20how%20to%20get%20selected%20item%20from%20a%20listbox.png"/></a></div>
<p>
Above is a sample dataset consisting of twenty data entries. This dataset includes various fields such as Medicine ID, Medicine Name, Unit, Price, Supplier Name, Address, Phone, Rating and Supply Time. Please note that this data is entirely fictional and created for example purposes only.
</p>
<p>
<b>Understanding the Listbox Properties</b><br>
Before diving into the code, it’s important to understand two crucial properties of the listbox: List and ListIndex. The List property represents the array of items in the listbox, while ListIndex refers to the index of the selected item.
</p>
<p>
The primary challenge in working with multicolumn listboxes is retrieving the user’s selection, particularly when the listbox contains several columns. Let’s consider this example user form.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwX8SKbuAlHtP5Fwz-X6ppjYf97QVBDFBBA0_yJ3ZwG9FYNqFbK8TZTGn8mZBjqvCEqNcuY9neVBvVrU5I3_X3UPKHtyuuVlDRVRcU99uy-WNER9_rbAeCOZlpesoQiv0PYniN9YeA-TruJBszMhdIoSxASYjZkAKNmh1LljAp6dzHp_lyhgYQuwkEDjc/s1600/Img%202%20-%20Sample%20VBA%20Listbox.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample VBA Listbox" border="0" data-original-height="735" data-original-width="1164" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwX8SKbuAlHtP5Fwz-X6ppjYf97QVBDFBBA0_yJ3ZwG9FYNqFbK8TZTGn8mZBjqvCEqNcuY9neVBvVrU5I3_X3UPKHtyuuVlDRVRcU99uy-WNER9_rbAeCOZlpesoQiv0PYniN9YeA-TruJBszMhdIoSxASYjZkAKNmh1LljAp6dzHp_lyhgYQuwkEDjc/s1600/Img%202%20-%20Sample%20VBA%20Listbox.png"/></a></div>
<p>
User has entered a value in the supplier name field and hit the search button. Now all the data related to that supplier name is shown in the listbox. Assume the name of the form is afrmViewDat and name of the listbox is lstSearchResult.
</p>
<h4 id="listindex_property">Using the ListIndex Property</h4>
<p>
The ListIndex property of a listbox is your starting point. The ListIndex property of a listbox returns the index of the selected item. However, it's important to remember that the index starts at 0. Here’s how you can use it.
</p>
<div class="vba-code-block">
Sub GetListIndex()<br><br>
Dim selectedIndex As Integer<br><br>
With frmViewData.lstSearchResult<br>
selectedIndex = .ListIndex<br>
End With<br><br>
MsgBox selectedIndex<br><br>
End Sub
</div>
<p>
So here is the result of the above subroutine.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKeGxmmLkMhWpzX0qRXwa0O1iKWMnJakrIHloeWDO4L6Tx6w6gIsYtj1HRigERjiNIRCN_Gyuku1Gqu9oLr3Bmq9Z4iujQv1DkYOdmINit9DIimGCXuEuleDM9d3aCtPmtXWW6yNrnGhMNXYsCXAWStfFLvSbJsvA4J-mUTl9__j-m1ER59pEmtMNRJhQ/s1600/Img%203%20-%20Listindex%20property%20returns%20indext%20of%20the%20selected%20item.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Listindex property returns index of the selected item" border="0" data-original-height="733" data-original-width="1164" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKeGxmmLkMhWpzX0qRXwa0O1iKWMnJakrIHloeWDO4L6Tx6w6gIsYtj1HRigERjiNIRCN_Gyuku1Gqu9oLr3Bmq9Z4iujQv1DkYOdmINit9DIimGCXuEuleDM9d3aCtPmtXWW6yNrnGhMNXYsCXAWStfFLvSbJsvA4J-mUTl9__j-m1ER59pEmtMNRJhQ/s1600/Img%203%20-%20Listindex%20property%20returns%20indext%20of%20the%20selected%20item.png"/></a></div>
<p>
This method is straightforward but only works well when single selection is enabled. Because if multiselect is on and if the user has selected multiple items, then this subroutine will only return the index of the item you selected lastly.
</p>
<p>
What will happen if the user doesn’t select any item? Then -1 will be returned as the result. So we can use this value to check whether the user has selected any item before executing the rest of the code.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKQK2NZ6TSIOE5Yj009YtR7UvWIyl9BYUCEQ2bYcirgXQiPLjSfuW5HEIvSN4NWINp97tg7mErUemPesy9sQucd5OulxcDh3dqBbUIyUpF3k-j5WW02Y-dERRP5WkKKaHZp5kPUFTIs2F_DNj6x-M_Gw4J2njNUWLxJNy666oa7LYnnh7B0QcZ5xje2tY/s1600/Img%204%20-%20-1%20is%20returned%20when%20no%20item%20is%20selected.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="-1 is returned when no item is selected" border="0" data-original-height="735" data-original-width="1167" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKQK2NZ6TSIOE5Yj009YtR7UvWIyl9BYUCEQ2bYcirgXQiPLjSfuW5HEIvSN4NWINp97tg7mErUemPesy9sQucd5OulxcDh3dqBbUIyUpF3k-j5WW02Y-dERRP5WkKKaHZp5kPUFTIs2F_DNj6x-M_Gw4J2njNUWLxJNy666oa7LYnnh7B0QcZ5xje2tY/s1600/Img%204%20-%20-1%20is%20returned%20when%20no%20item%20is%20selected.png"/></a></div>
<h4 id="extracting_value_using_list_property">Extracting Value from a Specific Column of the Selected Row - Using List Property</h4>
<p>
Once you have the row number, you can extract the value from a specific column using the List property. The List property can take two parameters: row index and column index. For instance, if you want to get the value from the second column of the selected row, you can use this approach.
</p>
<div class="vba-code-block">
Sub GetSelectedValue_Method1()<br><br>
Dim selectedIndex As Integer<br>
Dim selectedValue As String<br><br>
With frmViewData.lstSearchResult<br>
selectedIndex = .ListIndex<br>
If selectedIndex <> -1 Then<br>
selectedValue = .List(selectedIndex, 1) ' 1 for the second column<br>
Else<br>
selectedValue = "No selection"<br>
End If<br>
End With<br><br>
MsgBox selectedValue<br><br>
End Sub
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8YKFHcR6InsBmI0O_bRwKRTU4L7cznkS844JUWe18Kw3AKjfe2izf9cwLKnhG7v6svVONq804zHGYc9YMi9TO1ZMvfqZoRFLzZhfRf-NKCaY6TQiCMYjJ7chILWbxPL63ddc39-668ndQc_ek16EOAhtZaenXjxLX8z9K2YO7cBTfMFJ4Jdhv1nRN2JQ/s1600/Img%205%20-%20Get%20value%20of%20a%20particular%20column%20of%20the%20selected%20row%20of%20the%20listbox.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Get value of a particular column of the selected row of the listbox" border="0" data-original-height="732" data-original-width="1164" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8YKFHcR6InsBmI0O_bRwKRTU4L7cznkS844JUWe18Kw3AKjfe2izf9cwLKnhG7v6svVONq804zHGYc9YMi9TO1ZMvfqZoRFLzZhfRf-NKCaY6TQiCMYjJ7chILWbxPL63ddc39-668ndQc_ek16EOAhtZaenXjxLX8z9K2YO7cBTfMFJ4Jdhv1nRN2JQ/s1600/Img%205%20-%20Get%20value%20of%20a%20particular%20column%20of%20the%20selected%20row%20of%20the%20listbox.png"/></a></div>
<h4 id="handling_multiple_selections">Handling Multiple Selections For MultiSelect Enabled ListBoxes</h4>
<p>
Things get a bit trickier when dealing with listboxes which are set to allow multiple selections. In such cases, you’ll need to iterate through each item in the listbox, checking if it’s selected and then retrieving the required column values. Below subroutine will get values of the second column for all the selected rows.
</p>
<div class="vba-code-block">
Sub GetSelectedValues_ForMultiselect()<br><br>
Dim i As Integer<br>
Dim selectedValues As String<br><br>
With frmViewData.lstSearchResult<br>
For i = 0 To .ListCount - 1<br>
If .Selected(i) Then<br>
selectedValues = selectedValues & .List(i, 1) & "; "<br>
End If<br>
Next i<br>
End With<br><br>
MsgBox selectedValues<br><br>
End Sub
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjaCpJoo_2DGesRR7iL5HdVlW6p8gtLIbqWGkauOXj67jVpv_NDzPFy8m4JjvqTOo-av5ZnDuJc93J3vUXxcsbxjENY0iImijbLuPT54-ZypYEASu2uytRG9RWMg5zcpqpOAc2ztrkNFab3R2igKO1fqpYkGcsclqQYJuVBHjNAxpWwwuWGOhH8HTbgrTA/s1600/Img%206%20-%20Get%20values%20of%20a%20particular%20column%20for%20all%20the%20selected%20rows%20of%20a%20listbox.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Get values of a particular column for all the selected rows of a listbox" border="0" data-original-height="729" data-original-width="1159" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjaCpJoo_2DGesRR7iL5HdVlW6p8gtLIbqWGkauOXj67jVpv_NDzPFy8m4JjvqTOo-av5ZnDuJc93J3vUXxcsbxjENY0iImijbLuPT54-ZypYEASu2uytRG9RWMg5zcpqpOAc2ztrkNFab3R2igKO1fqpYkGcsclqQYJuVBHjNAxpWwwuWGOhH8HTbgrTA/s1600/Img%206%20-%20Get%20values%20of%20a%20particular%20column%20for%20all%20the%20selected%20rows%20of%20a%20listbox.png"/></a></div>
<h4 id="extracting_selected_values_using_column_property">Extracting Selected Value from a Listbox - Using Column Property</h4>
<p>
In the above examples, we learnt how to get a selected value using Listindex and List properties. However you can also use the Listindex with Column property to get the selected values from a listbox. Below example subroutine shows how you can get the column 3 value of the selected row.
</p>
<div class="vba-code-block">
Sub GetSelectedValue_Method2()<br><br>
Dim selectedValue As String<br><br>
With frmViewData.lstSearchResult<br>
If .ListIndex <> -1 Then<br>
selectedValue = .Column(2, .ListIndex) '2 for the third column<br>
Else<br>
selectedValue = "No selection"<br>
End If<br>
End With<br><br>
MsgBox selectedValue<br><br>
End Sub
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijbzgUPPGAK9oAQlTHNso6IGM2ZigDrijW0UoMKCKnfx9aEQZMpg1zAh0P62qnRPZU-dFllYA1igyCerxpX7ffgo4urvTmMZKFRFGveDorddbFruZQoYySW3h7_I6qz1nzMAcOk_KudvALCUz9E3rz6hr56BKr3UWzgThTEi_VrEXv5nw02fvp7HDnsW4/s1600/Img%207%20-%20Get%20selected%20value%20of%20a%20listbox%20using%20Listindex%20and%20column%20properties.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Get selected value of a listbox using Listindex and column properties" border="0" data-original-height="727" data-original-width="1164" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijbzgUPPGAK9oAQlTHNso6IGM2ZigDrijW0UoMKCKnfx9aEQZMpg1zAh0P62qnRPZU-dFllYA1igyCerxpX7ffgo4urvTmMZKFRFGveDorddbFruZQoYySW3h7_I6qz1nzMAcOk_KudvALCUz9E3rz6hr56BKr3UWzgThTEi_VrEXv5nw02fvp7HDnsW4/s1600/Img%207%20-%20Get%20selected%20value%20of%20a%20listbox%20using%20Listindex%20and%20column%20properties.png"/></a></div>
<h4 id="tips_and_tricks_get_selected_item_vba_listbox">Tips and Tricks for Effective Coding</h4>
<p>
Remember that VBA is zero-indexed: The first column is column 0, the second is column 1, and so on. Same for the rows. <br>
Always check if an item is selected in the listbox to avoid runtime errors.<br>
Use meaningful variable names for clarity and maintenance purposes.<br>
</p>
<p>
<b>Also read</b><br>
<a href="https://www.excelvbasolutions.com/2023/11/populate-userform-listbox-from-range.html">Populate Userform Listbox from Range</a><br>
<a href="https://www.excelvbasolutions.com/2022/01/add-horizontal-scrollbar-to-listbox.html">Add Horizontal Scrollbar to a Listbox</a><br>
<a href="https://www.excelvbasolutions.com/2022/01/fill-listbox-from-array.html">Fill a Listbox From an Array</a><br>
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-6713724409118364482024-01-02T08:43:00.000-08:002024-01-02T08:43:49.259-08:00Add Single Quotes to Excel Cells Using VBA<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In our previous post we learnt the uses of adding single quotes to the beginning of cells.
</p>
<a href="https://www.excelvbasolutions.com/2023/12/uses-of-adding-single-quotes-start-excel-cells.html">Uses of Adding Single Quotes to Start of Excel Cells</a>
<p>
In this lesson you will learn how to add single quotes to Excel cells using VBA. First of all, let’s see how we can do this manually in Excel. Because Excel shows unusual behavior when you add a single quote at the beginning of a cell.
</p>
<p>
Assume you want to add ‘53 to an Excel cell. Then when you enter '53 to an Excel cell it will show only 53 with a small green triangle at the upper left corner of the cell.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiVaWXSW2m4Dt_EQGtcnjoVVf1w8yMEacbtWWRtecDHSGrcfyYg6ZRthw8rfLrAdj_aFcA9SgzxxFGcYqOYMFbyVC6MbWZaiLyrM5FboQ8kuhM03M-XFO3F2nwCc-vcmI0iBuI4n9loVOEvprRRmHSEiwtC4dy_hjsojULpkfBL3c82OV8DmSurmplIUW0/s1600/Img%201%20-%20When%20added%20single%20quote%20before%20a%20number%20in%20a%20cell.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="When added single quote before a number in a cell" border="0" data-original-height="163" data-original-width="256" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiVaWXSW2m4Dt_EQGtcnjoVVf1w8yMEacbtWWRtecDHSGrcfyYg6ZRthw8rfLrAdj_aFcA9SgzxxFGcYqOYMFbyVC6MbWZaiLyrM5FboQ8kuhM03M-XFO3F2nwCc-vcmI0iBuI4n9loVOEvprRRmHSEiwtC4dy_hjsojULpkfBL3c82OV8DmSurmplIUW0/s1600/Img%201%20-%20When%20added%20single%20quote%20before%20a%20number%20in%20a%20cell.png"/></a></div>
<p>
But in the formula bar you can still see the single quote before the number.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfHb4Wd9ovJuZ2umzhOLVuKVNY9S9aucaPeP-Ldvz_DIfnlSUCiehQyT4Jb4ZQ49ItdN7LH67DaFPV7GJFFdsBf4DWkDY3WpV6UvezzP2BVCSW6VezSXFDClD3eVwIK72aJtGbf_l_Y70HeiPo25eJL4HfUiMbtYi65RxkaHElN0a2oklTdFwyPVLVqsY/s1600/Img%202%20-%20Formula%20bar%20still%20show%20the%20single%20quote%20before%20the%20number.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Formula bar still show the single quote before the number" border="0" data-original-height="262" data-original-width="343" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfHb4Wd9ovJuZ2umzhOLVuKVNY9S9aucaPeP-Ldvz_DIfnlSUCiehQyT4Jb4ZQ49ItdN7LH67DaFPV7GJFFdsBf4DWkDY3WpV6UvezzP2BVCSW6VezSXFDClD3eVwIK72aJtGbf_l_Y70HeiPo25eJL4HfUiMbtYi65RxkaHElN0a2oklTdFwyPVLVqsY/s1600/Img%202%20-%20Formula%20bar%20still%20show%20the%20single%20quote%20before%20the%20number.png"/></a></div>
<p>
Also when you select the cell a small icon will appear and if you take your cursor on top of it, you will see this kind of message.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijUrH7yCXGXj8I_zPIPk7ImRPzmKGpqB5lWI0HEFGl9w6O7UD9Ntlag5KDpH0gFpQ61SZ3YLAQZDYSP1SBtYX1_xweoSyDjtBiOV-I1tsUJh7CIN3cBOomrpx6t8LVidM3eMLDZ8fkPZWqazpEtN7hQoyP3kxuYT6O0EcsyZXWjQyE8Mm4tZYCosExzjo/s1600/Img%203%20-%20Message.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Message" border="0" data-original-height="180" data-original-width="604" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijUrH7yCXGXj8I_zPIPk7ImRPzmKGpqB5lWI0HEFGl9w6O7UD9Ntlag5KDpH0gFpQ61SZ3YLAQZDYSP1SBtYX1_xweoSyDjtBiOV-I1tsUJh7CIN3cBOomrpx6t8LVidM3eMLDZ8fkPZWqazpEtN7hQoyP3kxuYT6O0EcsyZXWjQyE8Mm4tZYCosExzjo/s1600/Img%203%20-%20Message.png"/></a></div>
<p>
Then what if we want to see a single quote at the beginning of the cell. Solution is simple. You need to add two single quotes.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfbqVKbir7i6H0ipKCqGuWvS7-Vd8Cg5OEwYrfzfoLjTWatrUkulwqTgLl0xS360aoHtPkRXmooMY3ORnJdP1_8J2wr9RBONztnyHTuK5V1ADtZ90tP-bTtzJ1X2IiN-sanyYFjI2FNqjWWq5FynfUBM6qjPb0y_Nz6dzziUfyaw-EeA-OPsn_2gHHq9g/s1600/Img%204%20-%20Add%20two%20single%20quotes.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Add two single quotes" border="0" data-original-height="206" data-original-width="347" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfbqVKbir7i6H0ipKCqGuWvS7-Vd8Cg5OEwYrfzfoLjTWatrUkulwqTgLl0xS360aoHtPkRXmooMY3ORnJdP1_8J2wr9RBONztnyHTuK5V1ADtZ90tP-bTtzJ1X2IiN-sanyYFjI2FNqjWWq5FynfUBM6qjPb0y_Nz6dzziUfyaw-EeA-OPsn_2gHHq9g/s1600/Img%204%20-%20Add%20two%20single%20quotes.png"/></a></div>
<p>
Here one single quote is shown in the cell. However you can see both single quotes in the formula bar.
</p>
<p>
Assume you want to add single quotes at both left and right of the content of the cell.<br>
Example - '53'<br>
How can we do that? To do this you need to add two single quotes at the beginning and only one single quote at the end like this.<br>
''53'
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGg7xsbgU4V_JdraqEDv2EBaxPe4uc0pq_2ktZIyLQtdlLS-C8qC6PDgi6kDa7D7_Eb3-Fr3bCEWMB__P6B63RREl08Xh2Nru5KqWi484vrIb7_Y2-qOq9MllVgwQiHXoiDJt8MfG6aqSehjBSxSay7Mj9g8YRJmnDVmPEMwMK7zUEC7tBGOsooOWPC60/s1600/Img%205%20-%20Add%20single%20quotes%20at%20both%20sides%20of%20the%20cell%20content.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Add single quotes at both sides of the cell content" border="0" data-original-height="183" data-original-width="332" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGg7xsbgU4V_JdraqEDv2EBaxPe4uc0pq_2ktZIyLQtdlLS-C8qC6PDgi6kDa7D7_Eb3-Fr3bCEWMB__P6B63RREl08Xh2Nru5KqWi484vrIb7_Y2-qOq9MllVgwQiHXoiDJt8MfG6aqSehjBSxSay7Mj9g8YRJmnDVmPEMwMK7zUEC7tBGOsooOWPC60/s1600/Img%205%20-%20Add%20single%20quotes%20at%20both%20sides%20of%20the%20cell%20content.png"/></a></div>
<p>
Now let’s see how we can add single quotes to Excel cells using VBA. When we automate this in VBA we need to consider the above behavior too.<br>
Let’s consider this sample Excel sheet.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgX_YFOwf6-lM62IdAn4mw-g-_pNQvgALfn1iHqJlHKdXU0geq4x5KUaAGXuMrFoZHJvk7qENW-FHWzIZYsdpAj9S8GplgIt6QfxaCg4s_F7Nh6eJbZoYVOi3381skOHH-aAhySJ9QmzIH6mRnqFf9dmrim5Zuxa49KwTiyVO3tjk_tCrIMGC8xlk3D7e8/s1600/Img%206%20-%20Sample%20Excel%20sheet.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample Excel sheet" border="0" data-original-height="274" data-original-width="259" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgX_YFOwf6-lM62IdAn4mw-g-_pNQvgALfn1iHqJlHKdXU0geq4x5KUaAGXuMrFoZHJvk7qENW-FHWzIZYsdpAj9S8GplgIt6QfxaCg4s_F7Nh6eJbZoYVOi3381skOHH-aAhySJ9QmzIH6mRnqFf9dmrim5Zuxa49KwTiyVO3tjk_tCrIMGC8xlk3D7e8/s1600/Img%206%20-%20Sample%20Excel%20sheet.png"/></a></div>
<p>
Sheet has 10 values in column A. Assume we want to add a single quote in front of each value. There are two ways to do this in VBA. We can use either ASCII code or we can use single quotes inside double quotes. First let’s see how we can do this using ASCII code. Assume the name of the worksheet is “My Data”.
</p>
<p>
<b>Method 1 - Using ASCII code</b>
</p>
<div class="vba-code-block">
Sub Add_Single_Quote()<br><br>
Dim WS As Worksheet<br>
Dim i As Integer<br><br>
Set WS = Worksheets("My Data")<br><br>
For i = 1 To 10<br>
WS.Range("A" & i).Value = Chr(39) & WS.Range("A" & i).Value<br>
Next i<br><br>
End Sub
</div>
<p>
In the above code Chr(39) represents the single quote character. Here you can find the full list of ASCII codes.
</p>
<a rel="nofollow" href="https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html">
ASCII Table</a>
<p>
Also a For loop is used to iterate through each value in column A.
</p>
<p>
<b>Method 2 - Using Single quotes directly inside double quotes</b>
</p>
<div class="vba-code-block">
Sub Add_Single_Quote_Method2()<br><br>
Dim WS As Worksheet<br>
Dim i As Integer<br><br>
Set WS = Worksheets("My Data")<br><br>
For i = 1 To 10<br>
WS.Range("A" & i).Value = "'" & WS.Range("A" & i).Value<br>
Next i<br><br>
End Sub
</div>
<p>
Below is the result we get when we run any of the above subroutines.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyG9A3Q7rc9NzMCwqGjUTkMfah2lRoZeJ6mXVfYPB5hSw16KR_CJ7AKyDFm8KMJsTzso3DtfnuxxrpStfl9No1Y-u_r-wiHIeKgNkrazM_5cqcRwqGcNxUTNGTz7nKGQLwiG2JuRWBXJlbROwi9ifiGiSOlJUIgoT3E9qTzTP55-_eJAX-KvcjE1Yjj2E/s1600/Img%207%20-%20Single%20quote%20is%20not%20shown%20in%20the%20result.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Single quote is not shown in the result" border="0" data-original-height="272" data-original-width="264" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyG9A3Q7rc9NzMCwqGjUTkMfah2lRoZeJ6mXVfYPB5hSw16KR_CJ7AKyDFm8KMJsTzso3DtfnuxxrpStfl9No1Y-u_r-wiHIeKgNkrazM_5cqcRwqGcNxUTNGTz7nKGQLwiG2JuRWBXJlbROwi9ifiGiSOlJUIgoT3E9qTzTP55-_eJAX-KvcjE1Yjj2E/s1600/Img%207%20-%20Single%20quote%20is%20not%20shown%20in%20the%20result.png"/></a></div>
<p>
Like in the manual scenario, we only get a green triangle at the upper left corner instead of the single quote. To show a single quote we need to add two single quotes using VBA. For that we can modify the above two macro as follows.
</p>
<p>
<b>Method 1</b>
</p>
<div class="vba-code-block">
Sub Add_Single_Quote()<br><br>
Dim WS As Worksheet<br>
Dim i As Integer<br><br>
Set WS = Worksheets("My Data")<br><br>
For i = 1 To 10<br>
WS.Range("A" & i).Value = Chr(39) & Chr(39) & WS.Range("A" & i).Value<br>
Next i<br><br>
End Sub
</div>
<p>
<b>Method 2</b>
</p>
<div class="vba-code-block">
Sub Add_Single_Quote_Method2()<br><br>
Dim WS As Worksheet<br>
Dim i As Integer<br><br>
Set WS = Worksheets("My Data")<br><br>
For i = 1 To 10<br>
WS.Range("A" & i).Value = "''" & WS.Range("A" & i).Value<br>
Next i<br><br>
End Sub
</div>
<p>
Now we will see a single quote before each value as expected.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfUC7xLdi49CPeHwhfEmc4izHWKFltt0Ftugo-0jFXw4wogj6dJ4IaKKIiQuBZUJXzncoKrwenaV6_Rrd_Vgr1WDtWZ5Tq80a00rbT91y7pjkdAaSwen0M4b2bQEk7HWszyoZZ4Cy-vepYImO8X2OgED4ChMrXizJIPKRxiojCGVV1sXlDSIMcXkKbN-A/s1600/Img%208%20-%20Single%20quotes%20is%20added%20in%20front%20of%20each%20value.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Single quotes is added in front of each value" border="0" data-original-height="271" data-original-width="272" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfUC7xLdi49CPeHwhfEmc4izHWKFltt0Ftugo-0jFXw4wogj6dJ4IaKKIiQuBZUJXzncoKrwenaV6_Rrd_Vgr1WDtWZ5Tq80a00rbT91y7pjkdAaSwen0M4b2bQEk7HWszyoZZ4Cy-vepYImO8X2OgED4ChMrXizJIPKRxiojCGVV1sXlDSIMcXkKbN-A/s1600/Img%208%20-%20Single%20quotes%20is%20added%20in%20front%20of%20each%20value.png"/></a></div>
<p>
Next let’s see how we can add a single quote at both sides of the cell content. Let’s consider this new sheet. Assume the name of the sheet is “Fruits”.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIYHvz9VsW15wlRLTycDmRHlBWbIy8OI5sk7fNxqs9CEip0VpTdBteCx8gfVkFsYoXe9v3SQDe9k2HT3kaSfLhDMpXjJ2v5Sl74ZVIbVpzCpLCjrNDS_sDlHo_bHAwWxohEOtMd7AZB0-_35qbKgKZNrhoVW9uak6hrPtLd40tP7Y6GFs2A2TkIl-atT8/s1600/Img%209%20-%20New%20example%20worksheet.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="New example worksheet" border="0" data-original-height="222" data-original-width="298" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIYHvz9VsW15wlRLTycDmRHlBWbIy8OI5sk7fNxqs9CEip0VpTdBteCx8gfVkFsYoXe9v3SQDe9k2HT3kaSfLhDMpXjJ2v5Sl74ZVIbVpzCpLCjrNDS_sDlHo_bHAwWxohEOtMd7AZB0-_35qbKgKZNrhoVW9uak6hrPtLd40tP7Y6GFs2A2TkIl-atT8/s1600/Img%209%20-%20New%20example%20worksheet.png"/></a></div>
<p>
Below are the two methods to add single quotes at either side of the fruit names.
</p>
<p>
<b>Method 1</b>
</p>
<div class="vba-code-block">
Sub Add_Single_Quotes_At_Both_Sides()<br><br>
Dim WS As Worksheet<br>
Dim i As Integer<br><br>
Set WS = Worksheets("Fruits")<br><br>
For i = 1 To 8<br>
WS.Range("A" & i).Value = Chr(39) & Chr(39) & WS.Range("A" & i).Value & Chr(39)<br>
Next i<br><br>
End Sub
</div>
<p>
<b>Method 2</b>
</p>
<div class="vba-code-block">
Sub Add_Single_Quotes_At_Both_Sides_Method2()<br><br>
Dim WS As Worksheet<br>
Dim i As Integer<br><br>
Set WS = Worksheets("Fruits")<br><br>
For i = 1 To 8<br>
WS.Range("A" & i).Value = "''" & WS.Range("A" & i).Value & "'"<br>
Next i<br><br>
End Sub
</div>
<p>
You will get this result if you run any of the above macros.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHdLMTlOY-roV7H4inO-JWHqzhwndNepPvg_aEME5t9c_0ofCbAWDowBM-I4JcnhOYzvKbYQdotyd6R292vMRInjutWSv9RcTqzaNjwPIgFLzOOgdQ_9f_-ulJyy2FINkLnHaZ4owPuyNLM7TTdrZU3B36Ga3acGjUlEo86sp-qLSpVOBgMvV0mPb0nac/s1600/Img%2010%20-%20Single%20quotes%20added%20at%20both%20sides%20of%20the%20cell%20content.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Single quotes added at both sides of the cell content" border="0" data-original-height="229" data-original-width="308" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHdLMTlOY-roV7H4inO-JWHqzhwndNepPvg_aEME5t9c_0ofCbAWDowBM-I4JcnhOYzvKbYQdotyd6R292vMRInjutWSv9RcTqzaNjwPIgFLzOOgdQ_9f_-ulJyy2FINkLnHaZ4owPuyNLM7TTdrZU3B36Ga3acGjUlEo86sp-qLSpVOBgMvV0mPb0nac/s1600/Img%2010%20-%20Single%20quotes%20added%20at%20both%20sides%20of%20the%20cell%20content.png"/></a></div>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-90117962744886851632023-12-25T05:49:00.000-08:002024-01-02T09:05:22.422-08:00Uses of Adding Single Quotes to Start of Excel Cells<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
Adding single quotes to the start of cells in Excel can be necessary in various scenarios to ensure data accuracy and proper interpretation. Here are a few scenarios where this technique might be useful.
</p>
<h4>Preserving Leading Zeros</h4>
<p>
When dealing with numeric codes or identifiers that begin with zeros, Excel might automatically remove leading zeros. Adding a single quote before such values prevents Excel from treating them as numbers, preserving the leading zeros.<br>
Example:<br>
00123 might become 123<br>
'00123 remains as is
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvThVay5NX7P1JDqCLUJWhyphenhyphenJoi2S6mhiQUJYwzcXBarZt002b2GdVf3gRxSqmMw0LVgt7JC6Rfa0UeOAU1iCnY6Ru-DJ_iT9nHIIeNft7pET7hPWAszzGRmneXXM9poqLfAFyF0fwy3scCx6ZhYNHn_lXse4HNqVfn2Gyt4nIhpAKn5kBCssoBIgbgQdM/s1600/Img%201%20-%20Preserving%20leading%20zeros%20using%20single%20quotes.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Preserving leading zeros using single quotes" border="0" data-original-height="182" data-original-width="447" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvThVay5NX7P1JDqCLUJWhyphenhyphenJoi2S6mhiQUJYwzcXBarZt002b2GdVf3gRxSqmMw0LVgt7JC6Rfa0UeOAU1iCnY6Ru-DJ_iT9nHIIeNft7pET7hPWAszzGRmneXXM9poqLfAFyF0fwy3scCx6ZhYNHn_lXse4HNqVfn2Gyt4nIhpAKn5kBCssoBIgbgQdM/s1600/Img%201%20-%20Preserving%20leading%20zeros%20using%20single%20quotes.png"/></a></div>
<h4>Preparing Data for SQL Queries</h4>
<p>
In SQL queries, single quotes are often used to denote string values. If you are creating SQL queries in Excel and have a list of values, adding single quotes ensures that they are recognized as strings.<br>
Example:<br>
Apple might become 'Apple'
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiAS5KphiYA3HJ8GlI4qA1vO6HuoD8oH5o0PPKO1sdotNTQxwucPl1UBjkkhsXHGrFpWVoawUm_6H7-gTBD298f1gZmcAmgx4EfoimIg-h_IGmG4G7Kn0ydvfCHsrnhPzOQoduY9MmWaoR2xbTC0-7LGGAugTaey_Wm3ZOKFCEfJTzM4xhYMNM0feT9tsw/s1600/Img%202%20-%20SQL%20query%20example.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="SQL query example" border="0" data-original-height="138" data-original-width="305" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiAS5KphiYA3HJ8GlI4qA1vO6HuoD8oH5o0PPKO1sdotNTQxwucPl1UBjkkhsXHGrFpWVoawUm_6H7-gTBD298f1gZmcAmgx4EfoimIg-h_IGmG4G7Kn0ydvfCHsrnhPzOQoduY9MmWaoR2xbTC0-7LGGAugTaey_Wm3ZOKFCEfJTzM4xhYMNM0feT9tsw/s1600/Img%202%20-%20SQL%20query%20example.png"/></a></div>
<h4>Handling Special Characters</h4>
<p>
If your data contains special characters that might have specific meanings in Excel or other applications, adding single quotes can help avoid misinterpretation.<br>
Example:<br>
=SUM(A1:A10) might be seen as a formula<br>
'=SUM(A1:A10) ensures it's treated as text
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja0e1em2ye7hdq4DgavuRaFMfLPvkoDDyjxg5phmTPs6YVd9kGAJ9nPk0wRyLCoMlkx7XQF48PxSZ9Khl_pv4-ExYArdIxEiZ0w2patH2y4QQADJ1Oj3GXQr7fO5Alb3yBYbDG01v2RgI-_Jxo5cLwaAyqqh8gPrl7F0AOrqer8B8SVpf1dULAN8VOjr4/s1600/Img%203%20-%20Show%20formulas%20using%20single%20quotes.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Show formulas using single quotes" border="0" data-original-height="142" data-original-width="382" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja0e1em2ye7hdq4DgavuRaFMfLPvkoDDyjxg5phmTPs6YVd9kGAJ9nPk0wRyLCoMlkx7XQF48PxSZ9Khl_pv4-ExYArdIxEiZ0w2patH2y4QQADJ1Oj3GXQr7fO5Alb3yBYbDG01v2RgI-_Jxo5cLwaAyqqh8gPrl7F0AOrqer8B8SVpf1dULAN8VOjr4/s1600/Img%203%20-%20Show%20formulas%20using%20single%20quotes.png"/></a></div>
<h4>Creating CSV Files</h4>
<p>
When creating Comma-Separated Values (CSV) files, adding single quotes to cells can be beneficial. It helps maintain the intended format, especially when dealing with leading zeros or text that might resemble numerical data.<br>
Example:<br>
01234, 56789 might become 1234, 56789<br>
'01234, 56789 remains as is
</p>
<p>
<b>Also read</b><br>
<a href="https://www.excelvbasolutions.com/2024/01/add-single-quotes-excel-cells-vba.html">Add Single Quotes to Excel Cells Using VBA</a><br>
<a href="https://www.excelvbasolutions.com/2021/02/How-to-quote-all-cells-of-a-csv-file.html">How To Quote All Cells Of A CSV File</a><br>
<a href="https://www.excelvbasolutions.com/2021/10/put-double-quotes-in-string-vba.html">How to Put Double Quotes in a String in VBA</a><br>
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-35761243743564685022023-12-19T04:10:00.000-08:002023-12-19T04:10:47.730-08:00Extract Formulas From Cells Using VBA<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In Excel, formulas are the backbone of data analysis and calculations. Extracting these formulas using VBA can be a powerful tool for various purposes. In this guide, we'll explore step by step how to use VBA to extract formulas from cells.
</p>
<p>
Here are a few scenarios where we need to extract formulas from cells using vba
</p>
<ul>
<li>To help in keeping track of changes made to formulas over time.</li>
<li>Analyze formulas to identify potential errors or inconsistencies.</li>
<li>Extracting formulas can help you analyze dependencies and relationships between different cells.</li>
<li>To partially automate the documentation process, providing insights of the logic behind calculations.</li>
</ul>
<p>
Now let’s see how we can develop a macro to extract a formula from a cell using VBA. First let’s see how we can get the formula from a particular cell we want. Let’s consider this example sheet.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZWPkkVHSYSQbe47aS2fPJhz3rqeWNlaubPLqJ0uP75BFmIbm-rEL_iMm8wCvEzieoHwBFMnXipoR0apVpLi3lYR6Mnwfikyj8FhiS5Sivc_De8ZMfT2142BVo5fkrGBuj-jiQaZNlx5RmY-NMBI9b3ptALFlHUNKBP4v9_PtC2yMuO7o6GgALTtR6uEI/s1600/Img%201%20-%20Sample%20worksheet%20with%20one%20formula.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample worksheet with one formula" border="0" data-original-height="402" data-original-width="365" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZWPkkVHSYSQbe47aS2fPJhz3rqeWNlaubPLqJ0uP75BFmIbm-rEL_iMm8wCvEzieoHwBFMnXipoR0apVpLi3lYR6Mnwfikyj8FhiS5Sivc_De8ZMfT2142BVo5fkrGBuj-jiQaZNlx5RmY-NMBI9b3ptALFlHUNKBP4v9_PtC2yMuO7o6GgALTtR6uEI/s1600/Img%201%20-%20Sample%20worksheet%20with%20one%20formula.png"/></a></div>
<p>
This worksheet has some values from B1 cell to B9 cell. Then I have put the following formula in cell B11.<br>
=SUM(B1:B9)
</p>
<p>
Assume the name of the worksheet is “Sheet1”. Then the following subroutine will show the formula of cell B11 in a message box.
</p>
<div class="vba-code-block">
Sub ExtractOneFormula()<br><br>
Dim WS As Worksheet<br><br>
Set WS = Worksheets("Sheet1")<br><br>
MsgBox WS.Range("B11").Formula<br><br>
End Sub
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQhGJq7zHNCukHg8BUARrv1gTkgLnPECfWA4DDZLrIvxhgt20ap03B1KWhDlhxypxO7MVXHBIRQFRcYarwdNmrr01KWLf9qzVnL5QmqtFjCkbs1tWAysw1tIKLqhQvvLg0Vwr4gMwDfytdDdA-azUQ53mWD2YM2uQoWbZdSBKePtY1uN7PobpapaskWsQ/s1600/Img%202%20-%20Macro%20will%20extract%20and%20show%20the%20formula%20in%20a%20message%20box.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Macro will extract and show the formula in a message box" border="0" data-original-height="235" data-original-width="262" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQhGJq7zHNCukHg8BUARrv1gTkgLnPECfWA4DDZLrIvxhgt20ap03B1KWhDlhxypxO7MVXHBIRQFRcYarwdNmrr01KWLf9qzVnL5QmqtFjCkbs1tWAysw1tIKLqhQvvLg0Vwr4gMwDfytdDdA-azUQ53mWD2YM2uQoWbZdSBKePtY1uN7PobpapaskWsQ/s1600/Img%202%20-%20Macro%20will%20extract%20and%20show%20the%20formula%20in%20a%20message%20box.png"/></a></div>
<p>
Now we learnt how to get a formula from a particular cell using VBA. Next let’s look at how to get a list of all the formulas in a sheet with cell addresses. Let’s consider this example Excel sheet.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdPdrY0k7qYOlISaBOCN7tsjosI_7sAat2MkDXhQvKdNTrx95_W2f256cMgcQJaJzI3-NfTBcCMLvNhEPOUIaB42uEQJ9nxKJKkfjcRGyEzn2wH29jhmfd9BhMdwAhAFk4v2i9JgljEoXauckW1XkVX8elOpoE0NutqSSVgyuTWi3mG8c4Quszi5-4Ltg/s1600/Img%203%20-%20Sample%20Excel%20sheet%20with%20lots%20of%20formulas.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample Excel sheet with lots of formulas" border="0" data-original-height="493" data-original-width="869" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdPdrY0k7qYOlISaBOCN7tsjosI_7sAat2MkDXhQvKdNTrx95_W2f256cMgcQJaJzI3-NfTBcCMLvNhEPOUIaB42uEQJ9nxKJKkfjcRGyEzn2wH29jhmfd9BhMdwAhAFk4v2i9JgljEoXauckW1XkVX8elOpoE0NutqSSVgyuTWi3mG8c4Quszi5-4Ltg/s1600/Img%203%20-%20Sample%20Excel%20sheet%20with%20lots%20of%20formulas.png"/></a></div>
<p>
In this worksheet, Total sales in column D is calculated using formulas. For an example D2 cell has following formula<br>
=B2*C2
</p>
<p>
Then Sales Ranking in column E is also calculated using formulas. For an example E2 cell has the following formula. <br>
=RANK.EQ(D2,$D$2:$D$11,0)
</p>
<p>
Also % of Total Sales in column F is calculated using formulas. F2 cell has following formula<br>
=D2/SUM($D$2:$D$11)
</p>
<p>
Then 3 fields(Grand Total Sales, Average Quantity Sold, Maximum Unit Price) in cells B13, B14 and B15 are calculated using following formulas.
</p>
<table style="border:1px solid;">
<tr>
<td style="border:1px solid;">Grand Total Sales</td><td style="border:1px solid;"> =SUM(D2:D11)</td>
</tr>
<tr>
<td style="border:1px solid;">Average Quantity Sold</td><td style="border:1px solid;"> =AVERAGE(B2:B11)</td>
</tr>
<tr>
<td style="border:1px solid;">Maximum Unit Price</td><td style="border:1px solid;">=MAX(C2:C11)</td>
</tr>
</table>
<p>
Then here is the macro to print all the formulas and their cell addresses in the immediate window
</p>
<div class="vba-code-block">
Sub ExtractFormulas()<br><br>
Dim WS As Worksheet<br>
Dim Rng As Range<br><br>
Set WS = Worksheets("Sheet2")<br><br>
For Each Rng In WS.UsedRange<br>
If Rng.HasFormula = True Then<br>
Debug.Print "Formula in " & Rng.Address & ": " & Rng.Formula<br>
End If<br>
Next Rng<br><br>
End Sub
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhefXXUY26uf21nEFP-tTmh9yb4noxq2wllWdvRG29DGKabl1gpKf5biDf_9BpOy_f4RPw26pfA8899hASeADfHG4p8OQE16b64RMny9-a9825D4xLpIqzyOJIpJrhylNbRlgqFGpI9EqytKK9idO8hD1ImbX_0KohlGuoDROXGWNNIMtuQls48Yq6b1H8/s1600/Img%204%20-%20All%20the%20formulas%20are%20extracted%20and%20printed%20in%20the%20immediate%20window.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="All the formulas are extracted and printed in the immediate window" border="0" data-original-height="774" data-original-width="652" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhefXXUY26uf21nEFP-tTmh9yb4noxq2wllWdvRG29DGKabl1gpKf5biDf_9BpOy_f4RPw26pfA8899hASeADfHG4p8OQE16b64RMny9-a9825D4xLpIqzyOJIpJrhylNbRlgqFGpI9EqytKK9idO8hD1ImbX_0KohlGuoDROXGWNNIMtuQls48Yq6b1H8/s1600/Img%204%20-%20All%20the%20formulas%20are%20extracted%20and%20printed%20in%20the%20immediate%20window.png"/></a></div>
<p>
In the above subroutine, the statement “If Rng.HasFormula = True Then” is used to identify the cells having formulas.
</p>
<p>
Also Rng.Address statement outputs the cell address of the cell and Rng.Formula statement output formula of that cell.
</p>
<p>
<b>Also read</b><br>
<a href="https://www.excelvbasolutions.com/2021/10/how-to-add-formula-to-cell-using-vba.html">How to Add a Formula to a Cell Using VBA</a><br>
<a href="https://www.excelvbasolutions.com/2021/06/access-formula-bar-keyboard-excel-2013.html">Access Formula Bar Using Keyboard</a><br>
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-59248573628887904452023-12-12T05:59:00.000-08:002023-12-12T05:59:55.612-08:00Extract Only Numbers From a String Using VBA<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In this lesson you will learn how to extract only numbers from a string using VBA. Here are some examples where extracting only numbers from a string can be useful.
</p>
<p>
<b>Data cleaning in Excel</b><br>
You have an Excel sheet with a column containing alphanumeric data, and you want to extract only the numeric part for analysis or calculation purposes.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9uIhQBfBSF2Xs6b2oPjf_Q_lgZvB2BpCxiCLk46JyKD0EGYzlxg4GNT6kHhBxjXIQG-GCMnPdrcNc0NUgeZWxR2W9ZjG7oYkZ6fkRj0lSuqr42Myufc71mt-kCr9mSevRK8U43j380KxFWQFQ_sRJFoKuNY9Lv8woOF1_GfQta1JBMTwEpn6FzLnuxz8/s1600/Img%201%20-%20Example%20worksheet%20showing%20how%20numbers%20are%20extracted%20from%20alphanumeric%20data.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Example worksheet showing how numbers are extracted from alphanumeric data" border="0" data-original-height="314" data-original-width="358" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9uIhQBfBSF2Xs6b2oPjf_Q_lgZvB2BpCxiCLk46JyKD0EGYzlxg4GNT6kHhBxjXIQG-GCMnPdrcNc0NUgeZWxR2W9ZjG7oYkZ6fkRj0lSuqr42Myufc71mt-kCr9mSevRK8U43j380KxFWQFQ_sRJFoKuNY9Lv8woOF1_GfQta1JBMTwEpn6FzLnuxz8/s1600/Img%201%20-%20Example%20worksheet%20showing%20how%20numbers%20are%20extracted%20from%20alphanumeric%20data.png"/></a></div>
<p>
<b>Financial Data Processing</b><br>
You are working with financial data that includes transaction descriptions, and you want to extract only the transaction amounts.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgL2dcYoB-UEe64AjOUDFYJVIHTD947lOr90ZCdEBgmNEMa3NAyuITK8AXPxKFvtbbJOlSGI1hGHwKvrcbW-1HdPH2ZdZQpvdLGWewxTv7bMa3VQtFolK6lr6EAgn2MnvKJ_DxVAJPkp-1cIwH3Rgrqt2jgmbXs4ggrIr692fAgYAfR4ylzt35rN8udYdE/s1600/Img%202%20-%20Only%20the%20amounts%20are%20extracted%20from%20transaction%20descriptions.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Only the amounts are extracted from transaction descriptions" border="0" data-original-height="300" data-original-width="559" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgL2dcYoB-UEe64AjOUDFYJVIHTD947lOr90ZCdEBgmNEMa3NAyuITK8AXPxKFvtbbJOlSGI1hGHwKvrcbW-1HdPH2ZdZQpvdLGWewxTv7bMa3VQtFolK6lr6EAgn2MnvKJ_DxVAJPkp-1cIwH3Rgrqt2jgmbXs4ggrIr692fAgYAfR4ylzt35rN8udYdE/s1600/Img%202%20-%20Only%20the%20amounts%20are%20extracted%20from%20transaction%20descriptions.png"/></a></div>
<p>
<b>Web Scraping</b><br>
You are scraping data from a website, and some of the retrieved text includes both numeric and non-numeric characters. You want to filter out only the numeric values.
</p>
<div class="separator" style="text-align: center;">
<a href="https://www.excelvbasolutions.com/p/vba-web-scraping-tutorial.html">
<img alt="" border="0" data-original-height="375" data-original-width="500" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgGiG2e0GDPZf639dCvKnsJpF6HuiEgXBBf2duk67MFI5QtMhWKdJ-G9ngdabeZszEWQtrR040nqpmK78zA3EqGVeph4ArPvjm0kJdG8gpIFt0xtF6vBgexmL4sIpWs5btLJh3mJ3iqHTyMLF_iKwlhICuwyLmHK3kWWVbyK6zVb3ViQu1s5wC3EOMg/s1600/ultimate%20guide%20to%20web%20scraping%20500%20width.png"/>
</a>
</div>
<p>
Above are a few scenarios where you may need to extract only numbers from a string using VBA.
</p>
<p>
Now let’s see how we can develop a VBA program to do this. Let’s create a function to extract numbers from a given string. Name of the function is ExtractNumbers. It takes one parameter, InputString, which is expected to be a string. The function return will also be a string. Below is the step by step guide on how to develop this function. You can find the completed function and test subroutine at the bottom.
</p>
<div class="vba-code-block">
Function ExtractNumbers(InputString As String) As String<br><br>
End Function
</div>
<p>
Next we need to declare 3 variables.
</p>
<div class="vba-code-block">
Dim i As Integer<br>
Dim Char As String<br>
Dim ResultString As String
</div>
<p>
i is used as a loop counter. Char represents a single character in the string. ResultString will store the extracted numbers.
</p>
<p>
A For loop is used to iterate through each character in the inputString. The loop starts from the first character (1) and continues until the length of the string (Len(inputString)).
</p>
<div class="vba-code-block">
For i = 1 To Len(InputString)<br><br>
Next i
</div>
<p>
Mid Function extracts a single character from the InputString at the position i and assigns it to the variable Char.
</p>
<div class="vba-code-block">
Char = Mid(InputString, i, 1)
</div>
<p>
Check this microsoft documentation to learn more about mid function.
</p>
<p>
<a href="https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/mid-function" target="_blank" >Mid function</a>
</p>
<p>
If Statement checks if the extracted character is numeric using the IsNumeric function.
</p>
<div class="vba-code-block">
If IsNumeric(Char) = True Then<br><br>
End If
</div>
<p>
Want to learn more about IsNumeric Function? Then check this post.<br><br>
<a href="https://www.excelvbasolutions.com/2020/11/isnumeric-function-vba-function.html">IsNumeric Function</a>
</p>
<p>
If the character is numeric, it is appended to the resultString
</p>
<div class="vba-code-block">
ResultString = ResultString & Char
</div>
<p>
Following line is used to return the extracted numbers as the result of the function.
</p>
<div class="vba-code-block">
ExtractNumbers = ResultString
</div>
<p>
Here is the full code of the ExtractNumbers function.
</p>
<div class="vba-code-block">
Function ExtractNumbers(InputString As String) As String<br><br>
Dim i As Integer<br>
Dim Char As String<br>
Dim ResultString As String<br><br>
'Loop through each character in the input string<br>
For i = 1 To Len(InputString)<br>
Char = Mid(InputString, i, 1)<br><br>
'Check if the character is a number<br>
If IsNumeric(Char) = True Then<br>
'Append the number to the result string<br>
ResultString = ResultString & Char<br>
End If<br>
Next i<br><br>
'Return the result string containing only numbers<br>
ExtractNumbers = ResultString<br><br>
End Function
</div>
<p>
Now let's create a subroutine to use the ExtractNumbers function on a sample string. This subroutine initializes a string, calls the function, and prints the extracted numbers in the Immediate Window.
</p>
<div class="vba-code-block">
Sub TestExtractNumbers()<br><br>
Dim originalString As String<br>
Dim result As String<br><br>
'Example string with alphanumeric characters<br>
originalString = "ProductA123"<br><br>
'Call the function to extract numbers<br>
result = ExtractNumbers(originalString)<br><br>
'Display the result in the Immediate Window<br>
Debug.Print result<br><br>
End Sub
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBZkA-3QFf0zketXnKYyWMKOQYzcOmmRr9QA96Gab0g1-BCB8a6PYzLh9XefqdDvwMnFeBrXdgsjEdw-P0Eik_er5CM948M18F4luADLlZKY6b_iSAz3DrbLYPlwWnkqF3647ylKQBBIzMSDH8IJ-8f_-hBE7qQsmcIQc9TtdR5f4dUCq3O3fVZDzB7xk/s1600/Img%203%20-%20Result%20is%20printed%20in%20the%20Immediate%20Window.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Result is printed in the Immediate Window" border="0" data-original-height="240" data-original-width="478" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBZkA-3QFf0zketXnKYyWMKOQYzcOmmRr9QA96Gab0g1-BCB8a6PYzLh9XefqdDvwMnFeBrXdgsjEdw-P0Eik_er5CM948M18F4luADLlZKY6b_iSAz3DrbLYPlwWnkqF3647ylKQBBIzMSDH8IJ-8f_-hBE7qQsmcIQc9TtdR5f4dUCq3O3fVZDzB7xk/s1600/Img%203%20-%20Result%20is%20printed%20in%20the%20Immediate%20Window.png"/></a></div>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-51699530532837708642023-12-07T03:55:00.000-08:002023-12-07T03:55:46.536-08:00Run VBA Code Automatically on Workbook Open<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In Excel automations, running VBA code upon workbook opening can streamline processes and boost efficiency. From this post you will explore the possibilities of this advanced feature, allowing you to tailor Excel to your unique needs and maximize productivity in your daily workflow. Then this article will guide you through the steps to run a VBA code when opening an Excel file using an example.
</p>
<p>
First of all let’s explore the possibility of this advanced feature.
</p>
<ul>
<li>
<b>Data Refresh:</b> If your workbook relies on external data sources, running VBA code on open can trigger an automatic refresh, ensuring that your data is always up-to-date.
</li>
<li>
<b>Security Measures:</b> You may want to use password prompts when opening the workbook, ensuring that only authorized users can use the file. For this you can use this technique to show a login form when opening the workbook. Check this post to learn how to show a userform automatically when opening an Excel file.<br>
<a href="https://www.excelvbasolutions.com/2021/04/show-userform-automatically-opening-excel-file.html">Show Userform Automatically When Opening Excel File</a>
</li>
<li>
<b>User Interface Customization:</b> You can use this technique to VBA to customize the workbook's interface, displaying specific sheets upon opening. For example, your workbook may have several worksheets and you may want to show only a particular worksheet on the workbook open. This is the usage I showed in the <a href="#example-1">example below.</a>
</li>
<li>
<b>Initialization Tasks:</b> Running VBA code on open is handy for initializing variables, setting default values, or configuring the environment to default state.
</li>
<li>
<b>Version Control:</b> You can use this technique to VBA to log information about when the workbook was last opened, helping with tracking changes.
</li>
<li>
<b>Connected Workbooks:</b> In scenarios where multiple workbooks are interlinked, running VBA code on open can establish connections.
</li>
<li>
<b>Alerts and Notifications:</b> Displaying alerts or notifications when opening the Excel VBA application. In some Excel VBA applications you might need to inform users about important updates or pending tasks whe he/she opens the application.
</li>
<li>
<b>Automated Backups:</b> This technique can be used to create an automatic backup system for your Excel VBA application. For an example you can tell the VBA to create a backup every time when a user opens the application. Or you can limit it to create only one backup per day if the user opens the application multiple times within one day.
</li>
</ul>
<p>
So now you explored various possibilities of this feature. Next let’s learn how to write a code to do this. I will explain this using an example.
</p>
<p id="example-1">
This example belongs to user interface customization. Assume your workbook has 3 worksheets called “Input”, “Report”, “Settings”. Suppose you want to only show the “Input” worksheet when the user opens the workbook hiding the other sheets. Users might be able to see other sheets using buttons while using the application.
</p>
<p>
Now first of all we need to develop a simple macro to show only the “Input” tab hiding other sheets.
</p>
<div class="vba-code-block">
Sub ShowOnlyInput()<br><br>
Worksheets("Input").Visible = True<br>
Worksheets("Report").Visible = xlVeryHidden<br>
Worksheets("Settings").Visible = xlVeryHidden<br><br>
End Sub
</div>
<p>
Note that there are different ways to hide worksheets using VBA. Some methods don't allow users to manually unhide sheets when hidden with VBA. Check this post if you like to learn more about hiding and unhiding worksheets in Excel.<br><br>
<a href="https://www.excelvbasolutions.com/2018/06/hide-and-unhide-worksheets-using-vba.html">Hide And Unhide Worksheets Using VBA</a><br>
</p>
<p>
We can put above simple code inside a module of the VBA project. Don’t know how to insert a module to a VBA project? Then check this post.<br><br>
<a href="https://www.excelvbasolutions.com/2023/11/insert-modules-excel-vba-projects.html">How to Insert Modules in Excel VBA Projects</a>
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEheTZHVRvfMk8aOoLfIlWnSnnroZetAAhVoO2mb0ec7x1aGvL3VNpMdioqDCGMocs6vysmm1ji2WM19Fwlpo4fhB03ZSbUiVwqm58WnHX4qUMJ3sVUa2xIELWZpa-PhSvZDz93a4VkTo5V8bLuNLWpdinTWbhYDiHiRzGb_1-Ae_R478XMBlRJegvd1Pog/s1600/Img%201%20-%20Add%20the%20code%20inside%20a%20module.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Add the code inside a module" border="0" data-original-height="550" data-original-width="917" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEheTZHVRvfMk8aOoLfIlWnSnnroZetAAhVoO2mb0ec7x1aGvL3VNpMdioqDCGMocs6vysmm1ji2WM19Fwlpo4fhB03ZSbUiVwqm58WnHX4qUMJ3sVUa2xIELWZpa-PhSvZDz93a4VkTo5V8bLuNLWpdinTWbhYDiHiRzGb_1-Ae_R478XMBlRJegvd1Pog/s1600/Img%201%20-%20Add%20the%20code%20inside%20a%20module.png"/></a></div>
<p>
Now we need a way to run this subroutine when the user opens the workbook. To do that we can use the workbook open event. Events are occurrences or triggers that happen within the Excel application, and VBA allows you to write code that responds to these events. So if you write a code inside the Workbook.Open event then it will be executed when the user opens the workbook.
</p>
<p>
Follow these easy steps to add code to the workbook open event.
</p>
<p>
Go to the VBA editor and double click on the ThisWorkbook Module.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizqEj4GmzBh9ModJC11KkkHeLcIaqZEvSUikAsWCyWux9cKVzg9SRQCmeJQIKomVKQO_2n4P93ObrN7XfnIeCwTGWtCQ3-pke71ZgOE2VmgERhpXHyQY0Bsk2ZSIBOtHi2wMFUhXx4vyUKI6cWLa84WSm767oyGhiVJMy2XbhdY-Le6EereWZOzgV29_8/s1600/Img%202%20-%20Double%20click%20on%20ThisWorkbook%20module.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Double click on ThisWorkbook module" border="0" data-original-height="470" data-original-width="843" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizqEj4GmzBh9ModJC11KkkHeLcIaqZEvSUikAsWCyWux9cKVzg9SRQCmeJQIKomVKQO_2n4P93ObrN7XfnIeCwTGWtCQ3-pke71ZgOE2VmgERhpXHyQY0Bsk2ZSIBOtHi2wMFUhXx4vyUKI6cWLa84WSm767oyGhiVJMy2XbhdY-Le6EereWZOzgV29_8/s1600/Img%202%20-%20Double%20click%20on%20ThisWorkbook%20module.png"/></a></div>
<p>
Now select “Workbook” from the first dropdown.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5gVFlATo8MTXUQxpbreyAoM5YGLUSGXz4ErjqzYf4I2DJBDaDG5ssymV6T8FNDePC-VDPbrpVCwpL5ppjPi07lwutJkTYc_P9uYyytXbUEAJOT-LGcnLzteSUiISgZKDteSaqoolu82_w4i-f1GxVOLLSPQCvE7vHhOwpjJrNBnCd-_xwNhahw7T6pcw/s1600/Img%203%20-%20Select%20Workbook%20from%20the%20first%20dropdown.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select Workbook from the first dropdown" border="0" data-original-height="418" data-original-width="1105" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5gVFlATo8MTXUQxpbreyAoM5YGLUSGXz4ErjqzYf4I2DJBDaDG5ssymV6T8FNDePC-VDPbrpVCwpL5ppjPi07lwutJkTYc_P9uYyytXbUEAJOT-LGcnLzteSUiISgZKDteSaqoolu82_w4i-f1GxVOLLSPQCvE7vHhOwpjJrNBnCd-_xwNhahw7T6pcw/s1600/Img%203%20-%20Select%20Workbook%20from%20the%20first%20dropdown.png"/></a></div>
<p>
When you select the “Workbook” from the dropdown, the second dropdown will be automatically changed to “Open” and the following code will be added to the ThisWorkbook module.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4OGrRoVw3OWn9UKKRtvoHuE7_-LlfXuxbD9tfQ7o9LFq0qQzgqAqEA0XRwa9WjCa2sd5LO0_bBa8QmD-4VPFaXQskMHKhL0rKS9cmX3FQrJks46LQubpaJ34880zZFbONr5bhuz0zKNsQrRRnfk_qLpQX9E6o3Cx0F9E9sDjp5ZsUICO87XCGp11rZ2M/s1600/Img%204%20-%20ThisWorkbook%20open%20event.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="ThisWorkbook open event" border="0" data-original-height="366" data-original-width="1108" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4OGrRoVw3OWn9UKKRtvoHuE7_-LlfXuxbD9tfQ7o9LFq0qQzgqAqEA0XRwa9WjCa2sd5LO0_bBa8QmD-4VPFaXQskMHKhL0rKS9cmX3FQrJks46LQubpaJ34880zZFbONr5bhuz0zKNsQrRRnfk_qLpQX9E6o3Cx0F9E9sDjp5ZsUICO87XCGp11rZ2M/s1600/Img%204%20-%20ThisWorkbook%20open%20event.png"/></a></div>
<p>
Also if you look at the second dropdown, you will notice that there are lots of other events available related to the Workbook object.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEV3wUG1F0LBjriC3JtRWrZYKJgzt3qrOS1RBBQNwu6Vh0dMkd5X3_95olWYKaBcdLosPFekpd0q-UGfw8nioQMWC101q7S3BPNFT9dcQaz52zn2XT4i95DD9k9vE4wGsEw2LqLHYB39YHtgY9EAox8FzUvzqGmSgk8UjUkpGC31QI-aguuUDU6MPxr0w/s1600/Img%205%20-%20Other%20events%20available%20for%20Workbook%20object.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Other events available for Workbook object" border="0" data-original-height="652" data-original-width="1101" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEV3wUG1F0LBjriC3JtRWrZYKJgzt3qrOS1RBBQNwu6Vh0dMkd5X3_95olWYKaBcdLosPFekpd0q-UGfw8nioQMWC101q7S3BPNFT9dcQaz52zn2XT4i95DD9k9vE4wGsEw2LqLHYB39YHtgY9EAox8FzUvzqGmSgk8UjUkpGC31QI-aguuUDU6MPxr0w/s1600/Img%205%20-%20Other%20events%20available%20for%20Workbook%20object.png"/></a></div>
<p>
Now we can run the previous subroutine we wrote by calling it from inside the Open event of the Workbook.
</p>
<div class="vba-code-block">
Private Sub Workbook_Open()<br><br>
Call ShowOnlyInput<br><br>
End Sub
</div>
<p>
Also instead of putting the code in a separate subroutine, you can put the code directly inside the Workbook_Open event as follows.
</p>
<div class="vba-code-block">
Private Sub Workbook_Open()<br><br>
Worksheets("Input").Visible = True<br>
Worksheets("Report").Visible = xlVeryHidden<br>
Worksheets("Settings").Visible = xlVeryHidden<br><br>
End Sub
</div>
<p>
But it is always a good practice to divide the code into meaningful sections. Because it enhances readability, maintainability, and overall code quality. When code is divided into sections, each part focuses on a specific task or functionality. This makes it easier for developers (including the original coder or others) to understand the purpose and flow of each section.
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-88178766814349435032023-11-28T04:23:00.000-08:002023-11-28T04:23:54.131-08:00How to Insert Modules in Excel VBA Projects<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
VBA (Visual Basic for Applications) is a powerful tool in Excel that allows users to automate tasks and enhance functionality. In this guide, we will walk you through the process of inserting a module into your Excel VBA project.
</p>
<p><b>Step 1: Accessing the Developer Tab</b></p>
<p>
Go to the "Developer" tab on the Excel ribbon. If you don't see the Developer tab, you may need to enable it in Excel's options. Check this previous post to learn how to enable the Developer tab in your Excel application.<br><br>
<a href="https://www.excelvbasolutions.com/2014/11/how-to-show-developer-tab-in-excel-2013.html">How to show the Developer tab in Excel</a><br>
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj67Qc_mSsiPQd0RmPvA9CUzrIR__xAeZyvlZIkz7281ds4vhgJDJfg8Z8mnEYMRv3JrqYrOS9LBaOeTPCOVgPOykpLpRDnyB6IXe2wjen9wycJxaTa-5cBoS0_5lSXJzWJ5L5ACaScap_JnjBLk30GsRdsi7Hy_pw10htRSzkeB5EsOBUDMMxu1RuRA_o/s1600/Img%201%20-%20Enable%20the%20Developer%20tab.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Enable the Developer tab" border="0" data-original-height="465" data-original-width="901" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj67Qc_mSsiPQd0RmPvA9CUzrIR__xAeZyvlZIkz7281ds4vhgJDJfg8Z8mnEYMRv3JrqYrOS9LBaOeTPCOVgPOykpLpRDnyB6IXe2wjen9wycJxaTa-5cBoS0_5lSXJzWJ5L5ACaScap_JnjBLk30GsRdsi7Hy_pw10htRSzkeB5EsOBUDMMxu1RuRA_o/s1600/Img%201%20-%20Enable%20the%20Developer%20tab.png"/></a></div>
<p><b>Step 2: Opening the VBA Editor</b></p>
<p>
Click on "Visual Basic" in the Developer tab. This action opens the VBA Editor, where you can create and manage your VBA code.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiz4eW_tq_9nDXzsG1BtFlLuPGLBwW1YC8sLtRuY_VflTtLK4BCEXBJnLg1FSHCO0qRk2DfGzUx8i4T8wvgeVJHT7dx_bzKxxIoF9EmqRYx1D49deIkJrJo8m7UZXbBuJpghRWEyDvUO1qmN7tYVuo2JDV4hqvmPOK2EQM030JjXiDlXsff2-OvSuffKZA/s1600/Img%202%20%20-%20Click%20Visual%20Basic%20in%20the%20Developer%20tab.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Click Visual Basic in the Developer tab" border="0" data-original-height="393" data-original-width="802" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiz4eW_tq_9nDXzsG1BtFlLuPGLBwW1YC8sLtRuY_VflTtLK4BCEXBJnLg1FSHCO0qRk2DfGzUx8i4T8wvgeVJHT7dx_bzKxxIoF9EmqRYx1D49deIkJrJo8m7UZXbBuJpghRWEyDvUO1qmN7tYVuo2JDV4hqvmPOK2EQM030JjXiDlXsff2-OvSuffKZA/s1600/Img%202%20%20-%20Click%20Visual%20Basic%20in%20the%20Developer%20tab.png"/></a></div>
<p><b>Step 3: Selecting the Workbook</b></p>
<p>
In the Project Explorer window on the left, click on the workbook for which you want to insert a module. This step is crucial if you have multiple workbooks open.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinVsh9ZdeufQj49xnAbAmyN5q5zfRaEv5rNxqx2UnSPdSTbmijjcyyc6Ae8uDNb-6tDNW3ELEAd1FtfOokXAf7d4m4YB_E4gzA8JesDQ4nQ9k_oKvlU4sUioSqHeD_jfoZ2BAGJ8jmyrOP9vQOigZhB4b1Ecj_VUNF73BLaoDW6HHwFISHkJXawC8T50s/s1600/Img%203%20-%20Select%20the%20workbook%20in%20the%20project%20explorer.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select the workbook in the project explorer" border="0" data-original-height="739" data-original-width="796" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinVsh9ZdeufQj49xnAbAmyN5q5zfRaEv5rNxqx2UnSPdSTbmijjcyyc6Ae8uDNb-6tDNW3ELEAd1FtfOokXAf7d4m4YB_E4gzA8JesDQ4nQ9k_oKvlU4sUioSqHeD_jfoZ2BAGJ8jmyrOP9vQOigZhB4b1Ecj_VUNF73BLaoDW6HHwFISHkJXawC8T50s/s1600/Img%203%20-%20Select%20the%20workbook%20in%20the%20project%20explorer.png"/></a></div>
<p>
In this example I’m going to insert the module to the VBA project of the Book2 file.
</p>
<p><b>Step 4: Inserting a Module</b></p>
<p>
From the menu, select "Insert" and then choose "Module." This command adds a new module under the selected workbook in the Project Explorer.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiaBvpu-xS7Q7YhdWemq_VW2to-z7xGANgaUiJvTTfQhcVNiThpfjbTgYhR5IryOukMGI32YuYawKtkWAKoO3v10db6Cmj5Imm74JR11R52LeYDIi4SKoD5McvljibKDrPVw_oVPQmZ3umYwuyXBlz3sxTAeirEWiKmSMzAzrn6k_bmlGWMkHE7KY6GDWw/s1600/Img%204%20-%20Insert%20module.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Insert module" border="0" data-original-height="436" data-original-width="610" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiaBvpu-xS7Q7YhdWemq_VW2to-z7xGANgaUiJvTTfQhcVNiThpfjbTgYhR5IryOukMGI32YuYawKtkWAKoO3v10db6Cmj5Imm74JR11R52LeYDIi4SKoD5McvljibKDrPVw_oVPQmZ3umYwuyXBlz3sxTAeirEWiKmSMzAzrn6k_bmlGWMkHE7KY6GDWw/s1600/Img%204%20-%20Insert%20module.png"/></a></div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVHB-GRPKQZTRpZKsVB28BElDEiv8hg-bCxoeLp38_0AOnugiORwUaxNhUm_WAVtUFBpf1gmvW-OnV_O8CxpwnUP0fRVTQvidYFSoeRL_3tClGFSH7ZWuMolz9aHh20keqNqfv7yDLoFUxWOI18iVt7bpfjqzhQBdcO_zFZ6sQblUKlgCtLOgUxHK-3PM/s1600/Img%205%20-%20A%20new%20module%20inserted%20to%20the%20VBA%20project.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="A new module inserted to the VBA project" border="0" data-original-height="715" data-original-width="760" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVHB-GRPKQZTRpZKsVB28BElDEiv8hg-bCxoeLp38_0AOnugiORwUaxNhUm_WAVtUFBpf1gmvW-OnV_O8CxpwnUP0fRVTQvidYFSoeRL_3tClGFSH7ZWuMolz9aHh20keqNqfv7yDLoFUxWOI18iVt7bpfjqzhQBdcO_zFZ6sQblUKlgCtLOgUxHK-3PM/s1600/Img%205%20-%20A%20new%20module%20inserted%20to%20the%20VBA%20project.png"/></a></div>
<p><b>Step 5: Opening the Module</b></p>
<p>
When you insert a new module, that module will be automatically open in the central editing area. If you have multiple modules in one or more VBA projects and if you want to add/edit or view code in a particular module, then double-click on the module you want. This action opens that particular module in the central editing area, allowing you to add/edit or view your VBA code.
</p>
<p>
Inserting a module provides a foundation for incorporating custom automation and functionalities into your Excel projects. With this guide, you can now easily insert VBA modules into your workbooks.
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-426033045235977052023-11-18T03:27:00.000-08:002023-11-18T03:27:22.675-08:00Populate Userform Listbox from Range<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In this lesson you will learn how to populate a userform listbox with a range. In VBA (Visual Basic for Applications), a list box is a graphical user interface control that allows users to make a selection from a list of items. It is commonly used in user forms to display data or present a list of options from which the user can choose. When it is used to present a list from which the user can select, the selected item or items in the list box can then be used for further processing in the other VBA codes associated with controls such as command buttons. Or by codes even associated with events such as listbox_click events etc.
</p>
<p>
A list box can contain a collection of items, typically displayed in a vertical list. These items can be static (defined at design time) or dynamic (populated at runtime). In this example we will use a collection of static items stored in a worksheet. If you want to populate the list box with a dynamic data set, then the best option is to populate data from an array. This post explains how to populate a listbox from an array.
</p>
<a href="https://www.excelvbasolutions.com/2022/01/fill-listbox-from-array.html">Fill a Listbox From an Array</a><br>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgtfWGQI3vVjUnAollNb23ev74A0hCuWL8MUJx6-7mBfSMCjR6DWM8kFADkU3xHKFfdGlDzKtCPAzIb42bjndoPJrDozJz1O1nqbpNOrEDXKfjKyaMbsUIhPD-GxT1tK3lzajXUtv4CDFbSP5R8sxztZFYr_-cwBDU5Bxo7s3q34GlJs7_OGVll_plMzzI/s1600/Img%201%20-%20Sample%20data%20in%20an%20Excel%20range.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample data in an Excel range" border="0" data-original-height="462" data-original-width="888" width="700" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgtfWGQI3vVjUnAollNb23ev74A0hCuWL8MUJx6-7mBfSMCjR6DWM8kFADkU3xHKFfdGlDzKtCPAzIb42bjndoPJrDozJz1O1nqbpNOrEDXKfjKyaMbsUIhPD-GxT1tK3lzajXUtv4CDFbSP5R8sxztZFYr_-cwBDU5Bxo7s3q34GlJs7_OGVll_plMzzI/s1600/Img%201%20-%20Sample%20data%20in%20an%20Excel%20range.png"/></a></div>
<p>
Name of this worksheet is “EmployeeData”. This worksheet contains Full Name, Job Title, Department, Employee ID and Date of Joining for 10 employees. Now let’s see how we can populate these data into a userform listbox. This is the listbox we are going to use for this example. Name of the form is frmEmployeeData and name of the listbox is lstEmployeeData.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_JVXzlZbrqZXKTJ8coYB_bOWrK2CbA9_QyipFnea4SUAhv_xCt-XPhjQ3hw9M8tX8aLJDY2ftmB25UOZzGe-axN6zEqNE8-TlYqFMqF7-POqu8kgIljAeJCZB1XQTCj4Qs3Xs2LjylgF73GPrblb7UH3NKK9DhNFZu88q5YcpVRHxm9COJh7wFIGF1I8/s1600/Img%202%20-%20VBA%20Userform%20Listbox.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="VBA Userform Listbox" border="0" data-original-height="773" data-original-width="1209" width="720" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_JVXzlZbrqZXKTJ8coYB_bOWrK2CbA9_QyipFnea4SUAhv_xCt-XPhjQ3hw9M8tX8aLJDY2ftmB25UOZzGe-axN6zEqNE8-TlYqFMqF7-POqu8kgIljAeJCZB1XQTCj4Qs3Xs2LjylgF73GPrblb7UH3NKK9DhNFZu88q5YcpVRHxm9COJh7wFIGF1I8/s1600/Img%202%20-%20VBA%20Userform%20Listbox.png"/></a></div>
<p>
Now we can write the vba code inside the UserForm_Initialize event to populate the listbox with Excel range.
</p>
<div class="vba-code-block">
Private Sub UserForm_Initialize()<br><br>
End Sub
</div>
<p>
This is how we can populate the list with the above Excel range.
</p>
<div class="vba-code-block">
Private Sub UserForm_Initialize()<br><br>
With lstEmployeeData<br>
.ColumnCount = 5<br>
.RowSource = "=EmployeeData!A1:E11"<br>
End With<br><br>
End Sub
</div>
<p>
This is how the listbox is populated from the Excel data range.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNdChj9o-Bt_yCRXE6J6dQLPSL4RbTDxWqDBF07_o-GB37BWSM8TdUfRPIbZtZdc5_Rf2TMrEyS2S9EQtkipXBUXlzbNTLGdTSJ3HYeoIqE0LRZLzES50jjw-mj_hHej8EPwIwJNhyphenhyphenFnsVeMDwdGR0nbZXfrcoZkg-GivV0uIfV6OhKESc7lkIyBQq35I/s1600/Img%203%20-%20Listbox%20populated%20from%20the%20range.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Listbox populated from the range" border="0" data-original-height="681" data-original-width="857" width="700" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNdChj9o-Bt_yCRXE6J6dQLPSL4RbTDxWqDBF07_o-GB37BWSM8TdUfRPIbZtZdc5_Rf2TMrEyS2S9EQtkipXBUXlzbNTLGdTSJ3HYeoIqE0LRZLzES50jjw-mj_hHej8EPwIwJNhyphenhyphenFnsVeMDwdGR0nbZXfrcoZkg-GivV0uIfV6OhKESc7lkIyBQq35I/s1600/Img%203%20-%20Listbox%20populated%20from%20the%20range.png"/></a></div>
<p>
Remember that you can’t use worksheet names having spaces.In the above example we use an Excel sheet called “EmployeeData”. Assume our worksheet name is “Employee Data”. Then we can’t modify the code as follows.
</p>
<div class="vba-code-block">
Private Sub UserForm_Initialize()<br><br>
With lstEmployeeData<br>
.ColumnCount = 5<br>
.RowSource = "=Employee Data!A1:E11"<br>
End With<br><br>
End Sub
</div>
<p>
Because then it will throw an error like this.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3eojQxr07T650znqE9z44IGapCI4BqGGu_BIHnH7PiEWlQgJnSEeOOCN6dHgHerLTJxDIn9ZwxsRr-ccmz6PsQRvs4gYh-0drWhIUK6_A2SbVrkMBlIUXJF5yWZ94UBfS3aL_AF3zzOJ5KvERFueCOdZRc0eZDoRLw3cVdObVUxg5iAoO_5xnxZyP2-g/s1600/Img%204%20-%20Error%20message%20when%20worksheet%20name%20contains%20space.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Error message when worksheet name contains space" border="0" data-original-height="238" data-original-width="515" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3eojQxr07T650znqE9z44IGapCI4BqGGu_BIHnH7PiEWlQgJnSEeOOCN6dHgHerLTJxDIn9ZwxsRr-ccmz6PsQRvs4gYh-0drWhIUK6_A2SbVrkMBlIUXJF5yWZ94UBfS3aL_AF3zzOJ5KvERFueCOdZRc0eZDoRLw3cVdObVUxg5iAoO_5xnxZyP2-g/s1600/Img%204%20-%20Error%20message%20when%20worksheet%20name%20contains%20space.png"/></a></div>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-45484103075013260462023-08-27T04:17:00.004-07:002023-08-27T04:18:30.867-07:00How to Test a Custom VBA Function in Immediate Window<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In this post I will show you how you can test a custom function in the immediate window. When you develop advanced VBA applications with multiple subroutines and functions you may need to test them while developing the code. Then you can use this technique to test individual functions without running the whole program. So now let’s look at how to call a user defined function from the immediate window. Here is a simple custom function I created to use as an example.
</p>
<div class="vba-code-block">
Function SumValues()<br><br>
Dim a As Long<br>
Dim b As Long<br>
Dim c As Long<br>
Dim Result As Long<br><br>
a = 1000<br>
b = 2000<br>
c = 3500<br><br>
Result = a + b + c<br>
SumValues = Result<br><br>
End Function
</div>
<br>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
This is a very simple function which returns the sum of three values. Now let’s see how we can test this function in the immediate window. First open the immediate window if it is not already opened.
</p>
<p>
<a href="https://www.excelvbasolutions.com/2020/11/immediate-window-Excel-2013-VBA.html">How to Show Immediate Window in VBA Environment</a>
</p>
<p>
When you open the immediate window you can test the custom function using one of the below two methods.
</p>
<p class="method-number-header">
Method 1
</p>
<p>
Enter the function name followed by a question mark.
</p>
<div class="vba-code-block">
?SumValues
</div>
<p>
So here is the result you will get.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_sgXRNUTsYmNtvUBA5LoBTUH78jD9T2qoBZOhBalSt81TMudm2X5crq1bPLtOKatq0ZMc12zmajZuqpOJW6deT6Uu2i6P1gbyJMovcBRxYpYCZhNpt8T0efGAsjRX6LQ4XlWpqZxl7vuAOUVhVz1o6JJ_CKU3mbeQlZTR9Ml7rWDtu-Kq-yZsNV-m/s1600/Img%201%20-%20Call%20a%20custom%20function%20in%20the%20immediate%20window.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Call a custom function in the immediate window" border="0" data-original-height="117" data-original-width="304" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_sgXRNUTsYmNtvUBA5LoBTUH78jD9T2qoBZOhBalSt81TMudm2X5crq1bPLtOKatq0ZMc12zmajZuqpOJW6deT6Uu2i6P1gbyJMovcBRxYpYCZhNpt8T0efGAsjRX6LQ4XlWpqZxl7vuAOUVhVz1o6JJ_CKU3mbeQlZTR9Ml7rWDtu-Kq-yZsNV-m/s1600/Img%201%20-%20Call%20a%20custom%20function%20in%20the%20immediate%20window.png"/></a></div>
<p>
That's one way to call a custom function from the immediate window.
</p>
<p class="method-number-header">
Method 2
</p>
<p>
In this method we are going to use the debug.print method to print the result of the function in the immediate window.
</p>
<p>
This is how you can test a custom VBA function in the immediate window using this second method.
</p>
<div class="vba-code-block">
debug.Print SumValues()
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg42NhbdC03LLshT8GesWzbT7ZHEvQXXi85cvLQwalVClOQVNcuifG4ktmwhz-BnlBTTR5Nu84P0q9VXKuf3aGDqwscj2lCfklmNwCSatgoW8_70a9FHu7NS4rydjr2urhwm52M2i_zKefcXtBqReHyNvg-mRA2JRFAKnclzP5y41wptAVDPIHmmTDg/s1600/Img%202%20-%20Test%20function%20in%20the%20immediate%20window%20using%20debug.print%20method.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Test function in the immediate window using debug.print method" border="0" data-original-height="127" data-original-width="262" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg42NhbdC03LLshT8GesWzbT7ZHEvQXXi85cvLQwalVClOQVNcuifG4ktmwhz-BnlBTTR5Nu84P0q9VXKuf3aGDqwscj2lCfklmNwCSatgoW8_70a9FHu7NS4rydjr2urhwm52M2i_zKefcXtBqReHyNvg-mRA2JRFAKnclzP5y41wptAVDPIHmmTDg/s1600/Img%202%20-%20Test%20function%20in%20the%20immediate%20window%20using%20debug.print%20method.png"/></a></div>
<p>
<b>Also read</b><br>
<a href="https://www.excelvbasolutions.com/2022/01/return-array-from-vba-function.html">How to Return an Array From VBA Function
</a><br>
<a href="https://www.excelvbasolutions.com/2022/01/pass-array-to-function-vba.html">How to Pass an Array to a VBA Function</a><br>
<a href="https://www.excelvbasolutions.com/2021/11/vba-instr-function-search-multiple-strings.html">How to Search For Multiple Strings Using VBA InStr Function</a><br>
<a href="https://www.excelvbasolutions.com/2020/02/besselj-function-Excel-functions.html">BESSELJ Function</a><br>
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-933839570141047482022-10-13T01:09:00.000-07:002022-10-13T01:09:17.053-07:00How to Clear the Immediate Window Using VBA<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
A VBA program can have multiple subroutines and functions. If you are a programmer you will need to test these subroutines and functions while developing the VBA code. Then the immediate window is a helpful tool you can use to test your components. If it is a subroutine, then you can print your variables using debug.print method to ensure whether they are calculated correctly. If it is a function you can print the return value in the immediate window.
</p>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
From one of our previous posts we learnt how to output data in VBA using a few different ways. In that post you can find how to output data to Immediate window using VBA.<br>
</p>
<p>
<a href="https://www.excelvbasolutions.com/2022/09/output-data-excel-vba.html">Output data in Excel VBA</a>
</p>
<p>
So today I'm going to show you how to clear the immediate window automatically using VBA. You may know how to clear it manually. If you don't know, follow these simple steps. First select everything in the immediate window. Then press the delete key on the keyboard to delete everything. If the immediate window is not visible you can use shortcut keys “Ctrl + G” to view the immediate window. Also if the cursor is in a different window than the immediate window, and if you press the above shortcut keys, then the cursor will move to the immediate window giving you access to the immediate window.
</p>
<p>
Now let’s look at how we can clear the immediate window using VBA. We can use the Application.Sendkeys method to clear the immediate window using VBA. Application.Sendkeys method lets us send keystrokes to the active application. So here is the order of keystrokes we need to send to clear the immediate window.
</p>
<p>
Ctrl + G<br>
Ctrl + A<br>
Delete
</p>
<p>
Ctrl + G will activate the immediate window. Then Ctrl + A will select everything in the immediate window. And Delete keystroke will delete the content from the immediate window. However in the Application.Sendkeys method, these keys are represented by one or more characters. Ctrl is represented by ^ character. You can simply use g and a keys to represent G and A respectively. and the delete key is represented by {DEL} characters. Check this documentation from Microsoft to see the codes of other available keys.
</p>
<p>
<a href="https://learn.microsoft.com/en-us/office/vba/api/excel.application.sendkeys" target="_blank" >Application.SendKeys method (Excel)</a>
</p>
<p>
So now you can rewrite the order of keystrokes in the Application.Sendkeys notation as follows.
</p>
<p>
^a^g{DEL}
</p>
<p>
Then you can develop the macro to clear the Immediate window using VBA as follows.
</p>
<div class="vba-code-block">
Sub ClearImmediateWindow()<br><br>
Application.SendKeys "^g^a{DEL}"<br><br>
End Sub
</div>
<p>
To test this macro, First I need to output something in the Immediate window. I will use the below macro to print “Hello, World!” hundred times in the immediate window.
</p>
<div class="vba-code-block">
Sub WriteHelloWorld()<br><br>
Dim i As Integer<br><br>
For i = 1 To 100<br>
Debug.Print "Hello, World!"<br>
Next i<br><br>
End Sub
</div>
<p>
This is how the Immediate window looks like when run the above macro.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizHhaBk949ubEUd7ceLfNuO-L4s7ZQm6Fg63RIgB0Ufd-PthUAR_QnTV2soqsmS49eKo0O6hsFhBwWkmXMfjUmeZjjG7927R6QYP47gD2_RWb_726ysq06R7LRugc8xc4d-xErrlNblDnFGgUS1kcxhnb5JTFrGAmnb-V0GymO6Q1Q-tNBRzOcPzvL/s1600/Img%201%20-%20Immediate%20window%20before%20clear%20the%20data.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Immediate window before clear the data" border="0" data-original-height="325" data-original-width="585" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizHhaBk949ubEUd7ceLfNuO-L4s7ZQm6Fg63RIgB0Ufd-PthUAR_QnTV2soqsmS49eKo0O6hsFhBwWkmXMfjUmeZjjG7927R6QYP47gD2_RWb_726ysq06R7LRugc8xc4d-xErrlNblDnFGgUS1kcxhnb5JTFrGAmnb-V0GymO6Q1Q-tNBRzOcPzvL/s1600/Img%201%20-%20Immediate%20window%20before%20clear%20the%20data.png"/></a></div>
<p>
Now let's run the ClearImmediateWindow subroutine to see how it clears the immediate window.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_1RW_VVWy7pysnU7T64v_e4WVtKTub49gaKIi5r537iSm419j4R74XpGyDdYw0ehnlUHG7sBW0To9tBXeRM2g_fWWXLZs5-X8LR7h-NkebNhgMNMj1F2hG2b10yZJHtyMjYC4cVppFow8ZlM0X1tYFJPGJZdx1JcpMbKezIHzr85mf73QUVIWE9WQ/s1600/Img%202%20-%20Immediate%20window%20after%20clear%20the%20data%20using%20VBA.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Immediate window after clear the data using VBA" border="0" data-original-height="324" data-original-width="586" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_1RW_VVWy7pysnU7T64v_e4WVtKTub49gaKIi5r537iSm419j4R74XpGyDdYw0ehnlUHG7sBW0To9tBXeRM2g_fWWXLZs5-X8LR7h-NkebNhgMNMj1F2hG2b10yZJHtyMjYC4cVppFow8ZlM0X1tYFJPGJZdx1JcpMbKezIHzr85mf73QUVIWE9WQ/s1600/Img%202%20-%20Immediate%20window%20after%20clear%20the%20data%20using%20VBA.png"/></a></div>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
However, using the Application.Sendkeys method is not advisable. Because unexpected things can happen if a user interacts with the Excel application while running the program. For example a whole code in your modules can be deleted if accidentally selected a module instead of the immediate window. So this is not a robust code to use in a VBA application. I suggest not to use the Application.Sendkeys method if there are any other options.
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-2927737907595825492022-10-06T02:54:00.002-07:002022-10-06T02:54:56.549-07:00How to Create a Column Chart Automatically Using VBA<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
Column charts are a chart type where data are represented from rectangles. In these charts, data are represented by vertical bars. Some people refer to these charts also as bar charts. But there is a difference between bar charts and column charts. If you interchange the x axis and y axis of a column chart then you will get a bar chart. Column charts make data easy to understand. Users will be able to understand the data at a glance when they are represented in column charts rather than in a written format. These charts are very helpful when we need to compare values of different categories. Column charts are more flexible than other chart types because you can plot lots of categories in one chart.
</p>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
So in this lesson I’m going to show you how to insert a column chart using VBA. I will use this sample Excel sheet to show you how to do this. This worksheet lists sales data of each month of a company.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjz7F8WMDK7wLtuguWLgMCrLK4NvUDX49DCqjjTA23pSVfvWHlRxd8uL7ZDDNgTFYrkw1YV6ro9inpb-kwCmZYY34m5Ao-hMvy1W0-W2eAHPEMsisqOZWKu1cMdIleG_J7epbyPYRuHAQdD3tyZEE1LMcqq_z7sDxTnrXwx9kqEiwRfdvP0ZQLsVBlS/s1600/Img%201%20-%20Sample%20data.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample Excel sheet" border="0" data-original-height="472" data-original-width="287" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjz7F8WMDK7wLtuguWLgMCrLK4NvUDX49DCqjjTA23pSVfvWHlRxd8uL7ZDDNgTFYrkw1YV6ro9inpb-kwCmZYY34m5Ao-hMvy1W0-W2eAHPEMsisqOZWKu1cMdIleG_J7epbyPYRuHAQdD3tyZEE1LMcqq_z7sDxTnrXwx9kqEiwRfdvP0ZQLsVBlS/s1600/Img%201%20-%20Sample%20data.png"/></a></div>
<p>
Assume the name of the worksheet is “Sales Data”. Then we can create a column chart automatically using the AddChart2 method available in VBA.
</p>
<div class="vba-code-block">
Sub CreateColumnChart()<br><br>
Dim WS As Worksheet<br><br>
Set WS = Worksheets("Sales Data")<br><br>
WS.Shapes.AddChart2(-1, xlColumn).Select<br>
ActiveChart.SetSourceData Source:=WS.Range("'Sales Data'!$A$1:$B$13")<br><br>
End Sub
</div>
<p>
This is the result of the above subroutine.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjINU0OG4GiyEmCOBlLGn5M1tZQenyxhM2ACq5Ypm_DxnQ3qv4lOUFU4fDlj2iNThhK22vsujPUgv0ZSxVgxJFwGMvE14a6gTSfVx428fFF9lZDtOWC002L6YFWiq15T1UzmJu14HjfAmqFbJN27S6dVhKX5f8VrZ8Ec6SExSVB3aTUaGd5Aistiwh0/s1600/Img%202%20-%20Column%20chart%20created%20automatically.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Column chart created automatically" border="0" data-original-height="561" data-original-width="699" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjINU0OG4GiyEmCOBlLGn5M1tZQenyxhM2ACq5Ypm_DxnQ3qv4lOUFU4fDlj2iNThhK22vsujPUgv0ZSxVgxJFwGMvE14a6gTSfVx428fFF9lZDtOWC002L6YFWiq15T1UzmJu14HjfAmqFbJN27S6dVhKX5f8VrZ8Ec6SExSVB3aTUaGd5Aistiwh0/s1600/Img%202%20-%20Column%20chart%20created%20automatically.png"/></a></div>
<p>
In the above VBA code I have used single quotes for the worksheet name. It is because we have a space character in the worksheet name. But if you don’t have a space character in your worksheet name then you can write it without quotes. For example if your worksheet name is “Data” then you can rewrite that line as follows.
</p>
<div class="vba-code-block">
ActiveChart.SetSourceData Source:=WS.Range("Data!$A$1:$B$13")
</div>
<p>
Also you can revise the above code using the Worksheet.Name property as well. This is how you can do it.
</p>
<div class="vba-code-block">
Sub CreateColumnChart_Ex2()<br><br>
Dim WS As Worksheet<br><br>
Set WS = Worksheets("Sales Data")<br><br>
WS.Shapes.AddChart2(-1, xlColumn).Select<br>
ActiveChart.SetSourceData Source:=WS.Range("'" & WS.Name & "'" & "!$A$1:$B$13")<br><br>
End Sub
</div>
<p>
I prefer this method because it is very easy to reuse or modify this code. For example if you want to use this for a different worksheet, then you need to change the worksheet name only in one line.
</p>
<p>
The AddChart2 method has several parameters. But all of them are optional. First parameter of the AddChart2 method is the style. In the above example, we used -1 as the first parameter of the AddChart2 method. If we set -1 as the style then we get the default style of the chart type specified in the second parameter. But we can create charts with various styles by changing this number. Here are some charts available in my Excel version.
</p>
<div class="vba-code-block">
Sub CreateColumnChart_Style209()<br><br>
Dim WS As Worksheet<br><br>
Set WS = Worksheets("Sales Data")<br><br>
WS.Shapes.AddChart2(209, xlColumn).Select<br>
ActiveChart.SetSourceData Source:=WS.Range("'" & WS.Name & "'" & "!$A$1:$B$13")<br><br>
End Sub
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8Th12cSSD88W2361yO5BGwXNGJwj5c5tidGVT-yK_ZtVWZjXzycyyanA29T6BbtE9rJmAPa3j2GmKDSt97Wb-O-wgZQ2Wdd8mOhvSdZg2UD4uj4IjC49aNKn32XBUCR2X59RiS0Wg5lIUh51dkaf9P-8asFvnoIsPw7SSYX3vIg5L52SQQGi5UItN/s1600/Img%203%20-%20Column%20chart%20created%20automatically%20with%20different%20style.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Column chart created automatically with different style" border="0" data-original-height="285" data-original-width="480" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8Th12cSSD88W2361yO5BGwXNGJwj5c5tidGVT-yK_ZtVWZjXzycyyanA29T6BbtE9rJmAPa3j2GmKDSt97Wb-O-wgZQ2Wdd8mOhvSdZg2UD4uj4IjC49aNKn32XBUCR2X59RiS0Wg5lIUh51dkaf9P-8asFvnoIsPw7SSYX3vIg5L52SQQGi5UItN/s1600/Img%203%20-%20Column%20chart%20created%20automatically%20with%20different%20style.png"/></a></div>
<p>Also Read<br>
<a href="https://www.excelvbasolutions.com/2022/03/vba-add-or-edit-chart-title.html">How to Add or Edit Chart Title Using VBA
</a><br>
<a href="https://www.excelvbasolutions.com/2021/09/swap-axis-of-excel-chart-without.html">Swap Axis of an Excel Chart Without Changing Excel Sheet Data</a><br>
<a href="https://www.excelvbasolutions.com/2020/07/find-name-of-active-chart-using-excel-vba.html">How to find the name of an active chart using VBA
</a><br>
</p>
<div class="vba-code-block">
Sub CreateColumnChart_Style208()<br><br>
Dim WS As Worksheet<br><br>
Set WS = Worksheets("Sales Data")<br><br>
WS.Shapes.AddChart2(208, xlColumn).Select<br>
ActiveChart.SetSourceData Source:=WS.Range("'" & WS.Name & "'" & "!$A$1:$B$13")<br><br>
End Sub
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhIjz-TySDCPlVchyL6oF5GiFwoa35-F134DPuDPSc7qD1sKmBYbl47q6IJ1vQU6ewJ61UyTFWHZLgsoG6nThOQ57UsDSbiSFvZx6NbBBWtg-XYgqPIyiguygIHq8wZjgfVbcwrds0GGwv5T0PK6LOlHSMept3mpPJvxahiyvgd-6tnuMOZR2wF4Q0h/s1600/Img%204%20-%20Column%20chart%20-%20style%20208.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Column chart - style 208" border="0" data-original-height="289" data-original-width="481" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhIjz-TySDCPlVchyL6oF5GiFwoa35-F134DPuDPSc7qD1sKmBYbl47q6IJ1vQU6ewJ61UyTFWHZLgsoG6nThOQ57UsDSbiSFvZx6NbBBWtg-XYgqPIyiguygIHq8wZjgfVbcwrds0GGwv5T0PK6LOlHSMept3mpPJvxahiyvgd-6tnuMOZR2wF4Q0h/s1600/Img%204%20-%20Column%20chart%20-%20style%20208.png"/></a></div>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
Not all the styles available in every Excel version. So you should first find the style number of your preferred chart before developing the code. You can easily find the style number by using the record macro option available in Excel application. Start recording a macro and then create a column chart with a style you prefer. Then find the style number from the code generated. Check this post if you want to learn more about the record macro option available in the Excel application.
</p>
<p>
<a href="https://www.excelvbasolutions.com/2020/12/excel-record-macro.html">How to Record a Macro in Excel</a>
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-87413985177899531002022-09-29T00:54:00.000-07:002022-09-29T00:54:00.488-07:00Output Data in Excel VBA<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
VBA can display data in a few different ways.
</p>
<ul>
<li>In the immediate window</li>
<li>In a message box</li>
<li>In an Excel sheet cell</li>
<li>In a label/textbox control of a userform</li>
</ul>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<h4>Display data in the immediate window</h4>
<p>
This is a data output method commonly used by developers to test subroutines and functions while developing VBA applications. In this method you can write data into the immediate window using the Debug.Print method. Here is an example.
</p>
<div class="vba-code-block">
Sub PrintIntoImmediateWindow()<br><br>
Debug.Print "Hello, World!"<br><br>
End Sub
</div>
<p>
This will write "Hello, World!" into the immediate window of the VBA editor.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhHiLXMnqmg1PtKMR_Y_P36WMJ83sB_b_Xh9TyyC2y-vyMI5o_Au5qcts8OxMDqT_oX6BMcy20VM8qqdABzcfASZbNMt1r7-XoebgMqWYtRsCXWRomDOA14q-FIfMUCLNMLN4VmuoVcNUMRMKI6nr6icFbwAbD36E-lD4wLoCU4kpOgumzI_menef8u/s1600/Img%201%20-%20Print%20data%20into%20immediate%20window.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Print data into immediate window of the VBA editor" border="0" data-original-height="240" data-original-width="515" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhHiLXMnqmg1PtKMR_Y_P36WMJ83sB_b_Xh9TyyC2y-vyMI5o_Au5qcts8OxMDqT_oX6BMcy20VM8qqdABzcfASZbNMt1r7-XoebgMqWYtRsCXWRomDOA14q-FIfMUCLNMLN4VmuoVcNUMRMKI6nr6icFbwAbD36E-lD4wLoCU4kpOgumzI_menef8u/s1600/Img%201%20-%20Print%20data%20into%20immediate%20window.png"/></a></div>
<h4>Display data in a message box</h4>
<p>
From this method you can output data in a message box. We often use this option to display the program completion messages to the users.
</p>
<div class="vba-code-block">
Sub ShowDataInMessagebox()<br><br>
MsgBox "Completed!"<br><br>
End Sub
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJTAgoF0WooMDhTq9hvS7BMYxRyEu_-vBGMTi5IoLNhn9n2S7GhvuncdorHJQHVq8RjHP3-bdsNFBGGgV9z9VLqfQDVOHFOPzPlJiE0SnCPNj6ZMGbf1Gee47fE9DwVVi6osQelDxe-qAMp2Ssey732ltPYHRBCYMlI3iXew7-cZJIySqFBZ0jzzEM/s1600/Img%202%20-%20Display%20data%20in%20a%20message%20box.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Display data in a message box" border="0" data-original-height="131" data-original-width="128" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJTAgoF0WooMDhTq9hvS7BMYxRyEu_-vBGMTi5IoLNhn9n2S7GhvuncdorHJQHVq8RjHP3-bdsNFBGGgV9z9VLqfQDVOHFOPzPlJiE0SnCPNj6ZMGbf1Gee47fE9DwVVi6osQelDxe-qAMp2Ssey732ltPYHRBCYMlI3iXew7-cZJIySqFBZ0jzzEM/s1600/Img%202%20-%20Display%20data%20in%20a%20message%20box.png"/></a></div>
<h4>Write data into a Excel sheet cell</h4>
<p>
You can also write data into Excel worksheets using VBA. This data output method is typically used when generating reports from VBA applications. You can generate sales reports, invoices etc through a VBA application using this method. Below is a very simplest example of this method. It will write "Hello, World!" into the cell A1 of the sheet1.
</p>
<div class="vba-code-block">
Sub PrintInWorksheet()<br><br>
Worksheets("Sheet1").Range("A1").Value = "Hello, World!"<br><br>
End Sub
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEisiP-2E5nrsXy-4HD0NI7luZ_f8zTMLfcjSr59PXfM8taaijbWoDcWJOXHEPr8q1RSdfRrK697WER5uLWcgqjHLYzDTPfs_Rkc37ulWBQ-rZTt-o7-0w1ZUJvXRL-r75zZS7g2IylsnhIfCULvnZN3TYVlMxAHsau7Bp5xzYk6rmjtakjsYoIs7Ave/s1600/Img%203%20-%20Write%20data%20to%20an%20Excel%20sheet.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Write data to an Excel sheet" border="0" data-original-height="303" data-original-width="387" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEisiP-2E5nrsXy-4HD0NI7luZ_f8zTMLfcjSr59PXfM8taaijbWoDcWJOXHEPr8q1RSdfRrK697WER5uLWcgqjHLYzDTPfs_Rkc37ulWBQ-rZTt-o7-0w1ZUJvXRL-r75zZS7g2IylsnhIfCULvnZN3TYVlMxAHsau7Bp5xzYk6rmjtakjsYoIs7Ave/s1600/Img%203%20-%20Write%20data%20to%20an%20Excel%20sheet.png"/></a></div>
<h4>Output data in a label/textbox control of a userform</h4>
<p>
This data output method can be used when developing applications with one or more userforms. If you have a userform in your form, then you can display data inside label and textbox controls. Below is a sample form I created to show how to output data in a textbox control of a userform. I’m going to develop a simple code to print “Hello, World!” when a user clicks the “Print” button. Assume the name of the textbox is “txtMessage” and the name of the command button is “cmdPrint”.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjYprBZO1Y5g3_UlEENyn4cs-Y_v7SPTxCEW5qw0K_w_yJojkpoXUmx-hSNQSF_VwLvRydNEtr75OWBQ9AAaenG_bA5BRnEbaBHuI5oHvPiNi-1iqI27kI6A6gjiXeX5oHj0QyRnDxX0bczVBU66TM2FBvb9V01qclWhEhc-T6UhFF-HFq4m-Dfq1fi/s1600/Img%204%20-%20Sample%20userform.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample userform" border="0" data-original-height="281" data-original-width="386" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjYprBZO1Y5g3_UlEENyn4cs-Y_v7SPTxCEW5qw0K_w_yJojkpoXUmx-hSNQSF_VwLvRydNEtr75OWBQ9AAaenG_bA5BRnEbaBHuI5oHvPiNi-1iqI27kI6A6gjiXeX5oHj0QyRnDxX0bczVBU66TM2FBvb9V01qclWhEhc-T6UhFF-HFq4m-Dfq1fi/s1600/Img%204%20-%20Sample%20userform.png"/></a></div>
<p>
Double click on the cmdPrint button. Then you will see this kind of click event in the userform code module.
</p>
<div class="vba-code-block">
Private Sub cmdPrint_Click()<br><br>
End Sub
</div>
<p>
Then add the following code to that click event.
</p>
<div class="vba-code-block">
txtMessage.Value = "Hello, World!"
</div>
<p>
So the completed code should look like this.
</p>
<div class="vba-code-block">
Private Sub cmdPrint_Click()<br><br>
txtMessage.Value = "Hello, World!"<br><br>
End Sub
</div>
<p>
Now when you click on the button, “Hello, World!” will be displayed in the textbox.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjsX9D5Ys8gohQqwPSMgpx2a3oahhpdUMwkgqbt7XmpzvuJA2NVwyHPoGxp98-PKQ7MEnKEX7jYIOpkbAosBAAtcLANGVqba_nfDD3Hvt7sIQkLFRqiNG1f4c_xuV-9EMQVirChCmRgNRDEAkOcEyh2hqN_4ET4snuejO5bZOyQAS0PLhTM4IQsCIj/s1600/Img%205%20-%20data%20printed%20in%20the%20userform%20textbox.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="data printed in the userform textbox" border="0" data-original-height="211" data-original-width="319" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjsX9D5Ys8gohQqwPSMgpx2a3oahhpdUMwkgqbt7XmpzvuJA2NVwyHPoGxp98-PKQ7MEnKEX7jYIOpkbAosBAAtcLANGVqba_nfDD3Hvt7sIQkLFRqiNG1f4c_xuV-9EMQVirChCmRgNRDEAkOcEyh2hqN_4ET4snuejO5bZOyQAS0PLhTM4IQsCIj/s1600/Img%205%20-%20data%20printed%20in%20the%20userform%20textbox.png"/></a></div>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
Also you can use TextBox.Text property instead of the value property as well.
</p>
<div class="vba-code-block">
txtMessage.Text = "Hello, World!"
</div>
<p>
<b>Also read</b><br>
<a href="https://www.excelvbasolutions.com/2014/08/open-and-read-text-file.html">Open and read text file using VBA</a><br>
<a href="https://www.excelvbasolutions.com/2018/12/convert-excel-sheet-to-pdf-using-vba.html">Convert an Excel Sheet to PDF Using VBA</a><br>
<a href="https://www.excelvbasolutions.com/2019/12/convert-entire-workbook-to-single-pdf.html">Convert an Entire Workbook to a Single PDF File</a><br>
<a href="https://www.excelvbasolutions.com/2014/07/open-files-in-specific-directory-folder.html">Open files in a specific directory (folder)</a><br>
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-8550478140258409462022-09-21T03:30:00.000-07:002022-09-21T03:30:55.001-07:00How to Find the Style Number of an Excel Chart Using VBA<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In this lesson you will learn how to find the style number of an Excel chart using VBA. Let’s consider this sample Excel sheet. This Excel sheet lists the number of sales for a few different items. Then an Excel chart has been used to visualize the sales of each item.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXpOQBjiH2Ot6Sa1G4VV2RaM380kpoKo_-OXRBkHbniuVdl_vpx2coEbgxtduUjH-zntouPJ91dfvaWulGhi7H2mGSqzgBCPEMQJcuITGFIGaNAvztfXHsmuuFwq1tqEI-h6yqMJh3tTU6fsEc1lkWnuVLKOgKGilunSWEkLj-KBq_Zwx6aWWN7NZl/s1600/Img%201%20-%20Excel%20worksheet%20containing%20a%20chart.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Excel worksheet containing a chart" border="0" data-original-height="683" data-original-width="577" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXpOQBjiH2Ot6Sa1G4VV2RaM380kpoKo_-OXRBkHbniuVdl_vpx2coEbgxtduUjH-zntouPJ91dfvaWulGhi7H2mGSqzgBCPEMQJcuITGFIGaNAvztfXHsmuuFwq1tqEI-h6yqMJh3tTU6fsEc1lkWnuVLKOgKGilunSWEkLj-KBq_Zwx6aWWN7NZl/s1600/Img%201%20-%20Excel%20worksheet%20containing%20a%20chart.png"/></a></div>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
Now let’s see how we can find the style number of this Excel chart using VBA. I will show you how to find the style number of an active chart and of a chart by its name. In the first example you will be able to find the style number of a selected chart.
</p>
<h4>Find style number of an active chart using VBA</h4>
<p>
In this example we are going to find the style number of an active chart. To find the style number from this method, first click on the chart you want to find the style number of.
</p>
<p>
Then run this simple subroutine.
</p>
<div class="vba-code-block">
Sub FindChartStyleNo_Method1()<br><br>
MsgBox ActiveChart.ChartStyle<br><br>
End Sub
</div>
<p>
This is the result obtained from the subroutine.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqcXjdsH1s5X0YmUU2HXX5RqQQI8vLY0QEkxte-Te8obffCYj5paxfz0dfTwu7xg0HmbP8mstF1sLDGFeBybBCRMuR0P4dPz2AYF81S4tfN_lGE6cWvVSZqAMPj3zoFjGcGJAyCA-dpVeUpt-b7Qq1HEi_urM74gtkiSfBEZfpgZdveZFGHJq6CgYN/s1600/Img%202%20-%20Style%20number%20of%20the%20active%20chart.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Style number of the active chart" border="0" data-original-height="201" data-original-width="215" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqcXjdsH1s5X0YmUU2HXX5RqQQI8vLY0QEkxte-Te8obffCYj5paxfz0dfTwu7xg0HmbP8mstF1sLDGFeBybBCRMuR0P4dPz2AYF81S4tfN_lGE6cWvVSZqAMPj3zoFjGcGJAyCA-dpVeUpt-b7Qq1HEi_urM74gtkiSfBEZfpgZdveZFGHJq6CgYN/s1600/Img%202%20-%20Style%20number%20of%20the%20active%20chart.png"/></a></div>
<h4>Find the style number of a chart by its name using VBA</h4>
<p>
From the previous subroutine we were able to get the style number of an active chart. You may know that each chart of a worksheet has a name. So in this next VBA macro we are going to find the style number of an Excel chart by its name. Remember that these names are not unique. Because users can create multiple charts with the same name.
</p>
<p>
Don’t know how to find the name of a chart? Check this post.<br>
<a href="https://www.excelvbasolutions.com/2020/07/find-name-of-chart-in-excel.html">Find the name of a chart in Excel</a>
</p>
<p>
Now let’s look at how to find the style number of a chart by its name. Assume that the name of our chart is “Chart 1”. Then we can find the style number of the chart using the following simple VBA macro.
</p>
<div class="vba-code-block">
Sub FindChartStyleNo_ByName()<br><br>
Dim MyChart As Chart<br><br>
Set MyChart = ActiveSheet.Shapes("Chart 1").Chart<br><br>
Debug.Print MyChart.ChartStyle<br><br>
End Sub
</div>
<p>
If we run the above macro the style number of the Excel chart will be printed in the immediate window like this.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhaa4bpNgjmOOxL3tvfSm20qUY-iW8_beIGWzCjh17BP_NUMMRiKqFncLzQBtoEk8gA7UvFc6AQmlF89rVsyyVZaZNYucOE7I2ZMITsNgMJG0aZU56OuKGvdLvr1jk1Z0IE7KN1STzOndwFRlsv6mURJFUsFwownHYG2TfQNNtNpqO6p7CVBinjb8gf/s1600/Img%203%20-%20Style%20number%20by%20chart%20name.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Style number by chart name" border="0" data-original-height="127" data-original-width="259" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhaa4bpNgjmOOxL3tvfSm20qUY-iW8_beIGWzCjh17BP_NUMMRiKqFncLzQBtoEk8gA7UvFc6AQmlF89rVsyyVZaZNYucOE7I2ZMITsNgMJG0aZU56OuKGvdLvr1jk1Z0IE7KN1STzOndwFRlsv6mURJFUsFwownHYG2TfQNNtNpqO6p7CVBinjb8gf/s1600/Img%203%20-%20Style%20number%20by%20chart%20name.png"/></a></div>
<p>
In this next example you will learn how to go through all the charts in the worksheet and print their names and style numbers. Here is the example sheet I’m going to use.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2inYME_myD88ojqfT3WxrMMpRhYGaw7W5o_K4r0Pj2X9Bdq2z-bLuLsrgq2s7LSxIYFiuK9OPDHXalYZYCNOiB4FMvmpuneu9u8h66_HHeXc-mf5YVh1zPw73aJ3ngal6Fg8Hs6DnutrOBRjmOzDCCPsE2r9DMbC8no_OerVo3hi4kLNbhBbE9aCX/s1600/Img%204%20-%20Excel%20worksheet%20with%20multiple%20charts.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Excel worksheet with multiple charts" border="0" data-original-height="610" data-original-width="572" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2inYME_myD88ojqfT3WxrMMpRhYGaw7W5o_K4r0Pj2X9Bdq2z-bLuLsrgq2s7LSxIYFiuK9OPDHXalYZYCNOiB4FMvmpuneu9u8h66_HHeXc-mf5YVh1zPw73aJ3ngal6Fg8Hs6DnutrOBRjmOzDCCPsE2r9DMbC8no_OerVo3hi4kLNbhBbE9aCX/s1600/Img%204%20-%20Excel%20worksheet%20with%20multiple%20charts.png"/></a></div>
<p>
Let’s name this subroutine as FindChartStyleNo_AllCharts
</p>
<div class="vba-code-block">
Sub FindChartStyleNo_AllCharts()<br><br>
End Sub
</div>
<p>
We need two variables for this subroutine.
</p>
<div class="vba-code-block">
Dim WS As Worksheet<br>
Dim Sh As Shape
</div>
<p>
Next we can assign the worksheet to the WS variable as follows.
</p>
<div class="vba-code-block">
Set WS = Worksheets("Sales data")
</div>
<p>
Now we need to iterate through all the shapes of the worksheet. We can use For Each statement to do that.
</p>
<div class="vba-code-block">
For Each Sh In WS.Shapes<br><br>
Next
</div>
<p>
Inside the For Each loop we need to separate only the charts. Because lots of other objects also belong to this shapes collection. So here we are going to use an If statement and the “Shape.Name” property to distinguish charts from other objects. Once charts are extracted then we can print the name and the style number in the immediate window.
</p>
<div class="vba-code-block">
If InStr(1, Sh.Name, "Chart", vbTextCompare) > 0 Then<br>
Debug.Print "Chart name - "; Sh.Name & " Style Number - " & Sh.Chart.ChartStyle<br>
End If
</div>
<p>
So here is the full code of this subroutine.
</p>
<div class="vba-code-block">
Sub FindChartStyleNo_AllCharts()<br><br>
Dim WS As Worksheet<br>
Dim Sh As Shape<br><br>
Set WS = Worksheets("Sales data")<br><br>
For Each Sh In WS.Shapes<br>
If InStr(1, Sh.Name, "Chart", vbTextCompare) > 0 Then<br>
Debug.Print "Chart name - "; Sh.Name & " Style Number - " & Sh.Chart.ChartStyle<br>
End If<br>
Next<br><br>
End Sub
</div>
<p>
This is the result of the above subroutine
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglq3RVrGjvJeMd5m9Y9XvR2QSs7A6eucuOnOfT9PG3ll7IVHUz7cLWkR5qrDw5HTF91dVbvHQFMAimLLVSfqLMT2dPcF4VLkzb6ULKGEver2ASsbx-TDQyTAhsyRZRjoKPOsUQFy4YMO1vU3FrjA-HkWDT009qaxg9RaurxeI7ZYSpZmgNmwkU2rFc/s1600/Img%205%20-%20Name%20and%20style%20number%20of%20multiple%20charts%20are%20printed%20in%20immediate%20window.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Name and style number of multiple charts are printed in immediate window" border="0" data-original-height="122" data-original-width="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglq3RVrGjvJeMd5m9Y9XvR2QSs7A6eucuOnOfT9PG3ll7IVHUz7cLWkR5qrDw5HTF91dVbvHQFMAimLLVSfqLMT2dPcF4VLkzb6ULKGEver2ASsbx-TDQyTAhsyRZRjoKPOsUQFy4YMO1vU3FrjA-HkWDT009qaxg9RaurxeI7ZYSpZmgNmwkU2rFc/s1600/Img%205%20-%20Name%20and%20style%20number%20of%20multiple%20charts%20are%20printed%20in%20immediate%20window.png"/></a></div>
<p>
But this method will only work when the user hasn't changed the chart name manually. If it is possible for the user to change the chart names then you can use the “Shapes.Type” property instead of the “Shapes.Name”. This is how you can modify the If statement section to use “Shapes.Type” property.
</p>
<div class="vba-code-block">
If Sh.Type = 3 Then<br>
Debug.Print "Chart type - "; Sh.Type & " Style Number - " & Sh.Chart.ChartStyle<br>
End If
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZf8Rw_IQrHsQ7DfFEQAaiZJU3R3RH4wHa7TLKKIoUXBNPsg6__C4bppUMgVC29091rdeKEb43cxojZjeMuQ3GQVnAIyZR1iaQCUdm3SAKxYV-s-TIqFZIXwGRkMTE8aB1xEhWZHniDxjg7g2IQeJOJURkXT4ebvPe0wAnGV3Cc3SZWe14vSUlukfG/s1600/Img%206%20-%20Type%20and%20style%20number%20of%20multiple%20charts%20are%20shown%20in%20the%20immediate%20window.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Type and style number of multiple charts are shown in the immediate window" border="0" data-original-height="134" data-original-width="377" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZf8Rw_IQrHsQ7DfFEQAaiZJU3R3RH4wHa7TLKKIoUXBNPsg6__C4bppUMgVC29091rdeKEb43cxojZjeMuQ3GQVnAIyZR1iaQCUdm3SAKxYV-s-TIqFZIXwGRkMTE8aB1xEhWZHniDxjg7g2IQeJOJURkXT4ebvPe0wAnGV3Cc3SZWe14vSUlukfG/s1600/Img%206%20-%20Type%20and%20style%20number%20of%20multiple%20charts%20are%20shown%20in%20the%20immediate%20window.png"/></a></div>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
3 is the MsoShapeType value that represents the charts. Check below article from Microsoft documentation to see the values for different types of shapes.
</p>
<a href="https://learn.microsoft.com/en-us/office/vba/api/office.msoshapetype" target="_blank">MsoShapeType enumeration (Office)</a>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-58207624363730807092022-09-15T00:32:00.005-07:002022-09-15T00:35:34.259-07:00Extract Numbers From a String Using VBA<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
When we develop VBA applications, sometimes we need to develop functions or subroutines to extract numbers from strings. So in this lesson you will learn a few different ways to extract numbers from a string using VBA.
</p>
<p>
Assume we have a string like this.
</p>
<p>
234sTsur45$p^
</p>
<p>
We are going to learn how to extract only 23445 from the above text string. There are few different ways to do this.
</p>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p class="method-number-header">
Method 1 - Using IsNumeric function
</p>
<p>
In this method we are going to use an inbuilt function called “IsNumeric” to extract only numbers from the string. Let’s name this subroutine as ExtractNumbers.
</p>
<div class="vba-code-block">
Sub ExtractNumbers()<br><br>
End Sub
</div>
<p>
First we need to declare a few variables.
</p>
<div class="vba-code-block">
Dim MyString As String<br>
Dim Tmp_Char As String<br>
Dim ResultString As String<br>
Dim i As Integer
</div>
<p>
Then we can assign our string to the MyString variable.
</p>
<div class="vba-code-block">
MyString = "234sTsur45$p^"
</div>
<p>
Next we need a For Next statement to iterate through each character of the string.
</p>
<div class="vba-code-block">
For i = 1 To Len(MyString)<br><br>
Next i
</div>
<p>
Inside this For Next statement we can use the Mid function to extract each character one by one. Each character will be assigned to the Tmp_Char variable temporarily.
</p>
<div class="vba-code-block">
For i = 1 To Len(MyString)<br>
Tmp_Char = Mid(MyString, i, 1)<br>
Next i
</div>
<p>
Now use IsNumeric function inside an If statement to check whether each character is a value or not. If the IsNumeric function returns true then we add that number to the ResultString variable.
</p>
<div class="vba-code-block">
For i = 1 To Len(MyString)<br>
Tmp_Char = Mid(MyString, i, 1)<br>
If IsNumeric(Tmp_Char) = True Then<br>
ResultString = ResultString & Tmp_Char<br>
End If<br>
Next i
</div>
<p>
Want to learn more about the IsNumeric function? Check this post.
</p>
<p>
<a href="https://www.excelvbasolutions.com/2020/11/isnumeric-function-vba-function.html">IsNumeric Function</a>
</p>
<p>
This is the complete code of the first method.
</p>
<div class="vba-code-block">
Sub ExtractNumbers()<br><br>
Dim MyString As String<br>
Dim Tmp_Char As String<br>
Dim ResultString As String<br>
Dim i As Integer<br><br>
MyString = "234sTsur45$p^"<br><br>
For i = 1 To Len(MyString)<br>
Tmp_Char = Mid(MyString, i, 1)<br>
If IsNumeric(Tmp_Char) = True Then<br>
ResultString = ResultString & Tmp_Char<br>
End If<br>
Next i<br><br>
Debug.Print ResultString<br><br>
End Sub
</div>
<p>
23445 will be printed in the immediate window when you run the above subroutine.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQswlQZ_H_QXMuviW3MkyMyPRPG_eXSOdeXc2SZB-N8dt74yFL28eNCXRtLjpOdNun5DEr-OWEHNUIOPb2rJeYOpkaRT3G0wW8RZPIiZvxC0Ns84MsGmohEPfJ-9ZhLu4zTzJLjcxipF-mrMCf_riHzQe9UifeZ3hGSltEb0vAZg13BQOpt2bNol04/s1600/Img%201%20-%20Numbers%20are%20extracted%20from%20the%20string.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Numbers are extracted from the string" border="0" data-original-height="106" data-original-width="216" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQswlQZ_H_QXMuviW3MkyMyPRPG_eXSOdeXc2SZB-N8dt74yFL28eNCXRtLjpOdNun5DEr-OWEHNUIOPb2rJeYOpkaRT3G0wW8RZPIiZvxC0Ns84MsGmohEPfJ-9ZhLu4zTzJLjcxipF-mrMCf_riHzQe9UifeZ3hGSltEb0vAZg13BQOpt2bNol04/s1600/Img%201%20-%20Numbers%20are%20extracted%20from%20the%20string.png"/></a></div>
<p class="method-number-header">
Method 2 - Using Select Case statement
</p>
<p>
In this method we are going to use Select Case statement instead of the If statement and IsNumeric function to extract numbers from the string. Below is the complete code of the second method.
</p>
<div class="vba-code-block">
Sub ExtractNumbers_Method2()<br><br>
Dim MyString As String<br>
Dim Tmp_Char As String<br>
Dim ResultString As String<br>
Dim i As Integer<br><br>
MyString = "234sTsur45$p^"<br><br>
For i = 1 To Len(MyString)<br>
Tmp_Char = Mid(MyString, i, 1)<br>
Select Case Tmp_Char<br>
Case 0 To 9<br>
ResultString = ResultString & Tmp_Char<br>
End Select<br>
Next i<br><br>
Debug.Print ResultString<br><br>
End Sub
</div>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
In this method Select Case statement is used to check whether the character is equal to value from 0 to 9. If the character is equal to value from 0 to 9 then those characters are appended to the ResultString.
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-28622401066231229482022-09-07T04:47:00.000-07:002022-09-07T04:47:58.163-07:00Return a String From VBA function<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
Function is a block of code which can be used multiple times inside a program. So you can omit writing the same code again and again by using functions. Also programmers can break down the problem into smaller segments by using the functions. This will help programmers to organize their codes in a more meaningful way. Functions normally return a value to the sub or to the function called them. So in this lesson you will learn how to return a string from a VBA function. Here is the syntax of a function which returns a string.
</p>
<p>
Function FunctionName() as string<br><br>
'-----------------------<br>
'Codes of the function<br>
'-----------------------<br><br>
FunctionName = ResultString<br><br>
End Function
</p>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
Above is the syntax of a function which has no arguments. So let’s create a very simple function which outputs a string using the above syntax.
</p>
<div class="vba-code-block">
Function WebsiteName()<br><br>
WebsiteName = "Excel-VBA Solutions"<br><br>
End Function
</div>
<p>
Above function returns the name of this website whenever it is called. Now you can call this function from a subroutine or from another function. This is how you can call the above function from a subroutine.
</p>
<div class="vba-code-block">
Sub Main()<br><br>
Dim Response As String<br><br>
Response = WebsiteName()<br><br>
Debug.Print Response<br><br>
End Sub
</div>
<p>
When you run the subroutine, the name of the website will be printed in the immediate window.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9APJhufYQgTlf7ziDImivpUuK7bZtSsuO324VLahoZXbj3AdtAPoHAVKHtDJFjIP9vW1_gTNOD9ySqOgXkB0kpyL42ilhMWUjEy07qQbqci_hlWPb4OFA_OV2Gv1iuKeKTAqL7unVPt8oFkDfq1w4WY6ATfB0GgKqbcx5gTNQDyjc_7R6vSpZxFyb/s1600/Img%201%20-%20String%20returned%20from%20the%20VBA%20function.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="String returned from the VBA function" border="0" data-original-height="120" data-original-width="317" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9APJhufYQgTlf7ziDImivpUuK7bZtSsuO324VLahoZXbj3AdtAPoHAVKHtDJFjIP9vW1_gTNOD9ySqOgXkB0kpyL42ilhMWUjEy07qQbqci_hlWPb4OFA_OV2Gv1iuKeKTAqL7unVPt8oFkDfq1w4WY6ATfB0GgKqbcx5gTNQDyjc_7R6vSpZxFyb/s1600/Img%201%20-%20String%20returned%20from%20the%20VBA%20function.png"/></a></div>
<p>
Next let’s look at how to develop a function which has an argument. Here is the syntax of a function having one argument.
</p>
<p>
Function FunctionName (Argument as type) as string<br><br>
'-----------------------<br>
'Codes of the function<br>
'-----------------------<br><br>
FunctionName = ResultString<br><br>
End Function
</p>
<p>
Type of the argument doesn’t need to be a string type. You can pass an argument of types such as Integer, Long, Boolean, Variant etc as well. Next let’s see how we can develop a function with an argument which returns a string. This is the sample Excel sheet I’m going to use for this example.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLyZv9ofkmNQSgnZwXWDXkoYuQHOKg3aqsiAS_Pu-y5zlsnUFLeSc4u_fhW_b-cRbQ1TMj8kDmecXV11QtGlJ42_Z5XC_h-FzOExcLJrEpZ173cHyYP7HNzndHZpYrFBIK2LNNNoO_EOtMUhAZoaaPCSRDwjiuoh-00IcdJB1MJhk9VuYv0e0HR4v2/s1600/Img%202%20-%20Sample%20Excel%20sheet.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample Excel sheet" border="0" data-original-height="386" data-original-width="290" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLyZv9ofkmNQSgnZwXWDXkoYuQHOKg3aqsiAS_Pu-y5zlsnUFLeSc4u_fhW_b-cRbQ1TMj8kDmecXV11QtGlJ42_Z5XC_h-FzOExcLJrEpZ173cHyYP7HNzndHZpYrFBIK2LNNNoO_EOtMUhAZoaaPCSRDwjiuoh-00IcdJB1MJhk9VuYv0e0HR4v2/s1600/Img%202%20-%20Sample%20Excel%20sheet.png"/></a></div>
<p>
For this example I’m going to create a function which can return the employee name when we pass Id as the argument. Let’s name this new function as FindName. We need to use a For Next statement inside our function to get the expected result. Assume the name of the worksheet is Data. You can develop the function as below to get the name of the employee when passing the Id as argument.
</p>
<div class="vba-code-block">
Function FindName(Id_no As Long) As String<br><br>
Dim WS As Worksheet<br>
Dim i As Integer<br>
Dim LastRow As Integer<br><br>
Set WS = Worksheets("Data")<br>
LastRow = WS.Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row<br><br>
For i = 2 To LastRow<br>
If WS.Range("A" & i).Value = Id_no Then<br>
FindName = WS.Range("B" & i).Value<br>
Exit Function<br>
End If<br>
Next i<br><br>
'If id not found<br>
FindName = ""<br><br>
End Function
</div>
<p>
So above is an example VBA function with an argument which returns a string. Program check for the matching id while iterating through each row number. If it finds a matching id then the function will return the corresponding name. Exit function statement is used to stop executing other lines of code once a function finds a match. If the Id is not found, the function will be executed til the end and will return an empty string. Here is how you can use the above function inside a subroutine.
</p>
<div class="vba-code-block">
Sub EmployeeData()<br><br>
Dim EmployeeName As String<br>
Dim IdNumber As Long<br><br>
IdNumber = 135421<br>
EmployeeName = FindName(IdNumber)<br><br>
MsgBox EmployeeName<br><br>
End Sub
</div>
<p>
Name of the relevant employee will be displayed in a message box when the code is executed.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdgzTTkwjI533WzV-llqlu5NN4J1d0xNU9rtyyZs9Yp8SsdbSozQAPz9-Ug9_jbrOYo60JUeY9YcfmTpSInigvZfkelteoDs59F3RdJ6SxHbltVG2aWBcuahSUTwy9YoyCv4mWP-b8Qhk0MRuO7iRtxHHEd1Gnh99h2dvaXrI25sD5UGJlsQ1pdgTd/s1600/Img%203%20-%20Function%20returned%20name%20as%20string.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Function returned name as string" border="0" data-original-height="135" data-original-width="134" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdgzTTkwjI533WzV-llqlu5NN4J1d0xNU9rtyyZs9Yp8SsdbSozQAPz9-Ug9_jbrOYo60JUeY9YcfmTpSInigvZfkelteoDs59F3RdJ6SxHbltVG2aWBcuahSUTwy9YoyCv4mWP-b8Qhk0MRuO7iRtxHHEd1Gnh99h2dvaXrI25sD5UGJlsQ1pdgTd/s1600/Img%203%20-%20Function%20returned%20name%20as%20string.png"/></a></div>
<p>
This is what happens when you pass an Id which is not available in the worksheet.
</p>
<div class="vba-code-block">
Sub EmployeeData()<br><br>
Dim EmployeeName As String<br>
Dim IdNumber As Long<br><br>
IdNumber = 135429<br>
EmployeeName = FindName(IdNumber)<br><br>
MsgBox EmployeeName<br><br>
End Sub
</div>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtO2-po9IoTUpETRS6kIPhvpy6l1jRlVf0BGYq_6FoQNt-NuWHaEiCThBNrGzMWuspvRLNx1hsxkBYrTFlUGd8uQdA7zLGj6GA9g_4Iarz_Mc0Eek2JtJUfXINjB6kHuGICOrj6IYtNnY3DSlYQI5ksZqTzCAK9l1vGj9rqdelgU04FbqBLB1IWAUK/s1600/Img%204%20-%20Function%20returns%20an%20empty%20string.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Function returns an empty string" border="0" data-original-height="123" data-original-width="133" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtO2-po9IoTUpETRS6kIPhvpy6l1jRlVf0BGYq_6FoQNt-NuWHaEiCThBNrGzMWuspvRLNx1hsxkBYrTFlUGd8uQdA7zLGj6GA9g_4Iarz_Mc0Eek2JtJUfXINjB6kHuGICOrj6IYtNnY3DSlYQI5ksZqTzCAK9l1vGj9rqdelgU04FbqBLB1IWAUK/s1600/Img%204%20-%20Function%20returns%20an%20empty%20string.png"/></a></div>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-81939343286743780552022-09-01T03:14:00.003-07:002022-09-01T03:15:49.112-07:00How to Sum a Row in Excel<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In this lesson you will learn how to sum a row in Excel. I will show you two methods to get the total of an Excel row. Let’s consider this sample Excel sheet. We have names of students in column A. Then we have marks of five tests in the next five columns. Assume we want to calculate the total of five tests for each student.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0TLcyI0vXJKABoR-MLRfa9X5KTf1xlmFAsLhJJ_qyrYDshJmZv4dpPjW8TLAxojYxBcswM-IPx1RaWfwCcZHM_-MVutWmsFQOGRaMo7Mdz7KihLykA7ZHM_hizZaCBvx1Vaxorx4DXraDrkirMedaSCqLA3zXg82wkSv2jarQ2aVEx8eZnf_JWQ6u/s1600/img%201%20-%20sample%20data.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample data" border="0" data-original-height="416" data-original-width="505" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0TLcyI0vXJKABoR-MLRfa9X5KTf1xlmFAsLhJJ_qyrYDshJmZv4dpPjW8TLAxojYxBcswM-IPx1RaWfwCcZHM_-MVutWmsFQOGRaMo7Mdz7KihLykA7ZHM_hizZaCBvx1Vaxorx4DXraDrkirMedaSCqLA3zXg82wkSv2jarQ2aVEx8eZnf_JWQ6u/s1600/img%201%20-%20sample%20data.png"/></a></div>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p class="method-number-header">
Method 1
</p>
<p>
In the above example Excel sheet we want to get the sum of each row to the column G. First let’s look at how to sum a row in Excel for one row. Then we can apply similar formulas for other rows as well. Here are the steps to follow. First click on the G2 cell. Next go to the “FORMULAS” tab in the Excel ribbon.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNWgRPxFnJ7yxhshYgRTE6sgOzn3er5-Eyyavb5nds0n6LWcQvLI7VJNpJ9Z2VZ-6OGFXnsPQtwt1c5229QeEXrHzZCEnwhsdFAk8RSuHAUYaAnztalNy9NV500lV8G1R3ZB-XK3thFbq5AZNr7uJIUCytgE4dlja0qHj_PE0J8c1VM9Xi2fzE2ylc/s1600/Img%202%20-%20Select%20cell%20and%20go%20to%20Formulas%20tab.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select cell and go to Formulas tab" border="0" data-original-height="491" data-original-width="539" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNWgRPxFnJ7yxhshYgRTE6sgOzn3er5-Eyyavb5nds0n6LWcQvLI7VJNpJ9Z2VZ-6OGFXnsPQtwt1c5229QeEXrHzZCEnwhsdFAk8RSuHAUYaAnztalNy9NV500lV8G1R3ZB-XK3thFbq5AZNr7uJIUCytgE4dlja0qHj_PE0J8c1VM9Xi2fzE2ylc/s1600/Img%202%20-%20Select%20cell%20and%20go%20to%20Formulas%20tab.png"/></a></div>
<p>
Then click on the AutoSum
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiakqa06SxfVA5CYFgkVxNwOLWQH-wSSE4BQSzmMQVxgQc2wXiQXpFvUa8pd6jW1cB9ENlaQiA-Py5LsJzJzdgWcaWYhC5PwASLh0reiVr7hBunv-aitVtslyeBUIz-bRh3EwfM4skRaMrvMtYGMmjeK8wTm3Hq2vmyDJ8DKcEgQ3PCCwnxGn-hvE6/s1600/Img%203%20-%20Click%20on%20AutoSum.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Click on AutoSum" border="0" data-original-height="167" data-original-width="522" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiakqa06SxfVA5CYFgkVxNwOLWQH-wSSE4BQSzmMQVxgQc2wXiQXpFvUa8pd6jW1cB9ENlaQiA-Py5LsJzJzdgWcaWYhC5PwASLh0reiVr7hBunv-aitVtslyeBUIz-bRh3EwfM4skRaMrvMtYGMmjeK8wTm3Hq2vmyDJ8DKcEgQ3PCCwnxGn-hvE6/s1600/Img%203%20-%20Click%20on%20AutoSum.png"/></a></div>
<p>
Then you will see that the Sum formula is automatically inserted to the selected cell.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFgR3iGhn1_5nqyRYOIdeI1ZfUydDeP2kA5aoN-QDxeHbxaYHEMeooQqlvGZ9Kj2T_L9ikbOCKL6pZ3uwMNN5UYMR2Ei8GJK0UofxCXn3nJsv4aQe2SdCRO1xQgZ6D9RmJMhBLLPKK55CmwT6SDYLzAKtadRuuqzAu_p8yV6fC2S-dLzKlst0eFUaO/s1600/Img%204%20-%20Sum%20formula%20is%20automatically%20inserted.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sum formula is automatically inserted" border="0" data-original-height="307" data-original-width="518" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFgR3iGhn1_5nqyRYOIdeI1ZfUydDeP2kA5aoN-QDxeHbxaYHEMeooQqlvGZ9Kj2T_L9ikbOCKL6pZ3uwMNN5UYMR2Ei8GJK0UofxCXn3nJsv4aQe2SdCRO1xQgZ6D9RmJMhBLLPKK55CmwT6SDYLzAKtadRuuqzAu_p8yV6fC2S-dLzKlst0eFUaO/s1600/Img%204%20-%20Sum%20formula%20is%20automatically%20inserted.png"/></a></div>
<p>
Now press enter. Total value will be calculated like this. So this is one way to sum a row in Excel.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh5JKLux7q0CljtzZePBJufXLd5BCrCViFVwp7bkC1_iuuy2u9U1rbsAnP2uN02gIhmovnTj9y3vvZgfRR3LX--vf-E2wgoMQwzBxwAX54QExKavlzayMH3BrC0uIEQBKpMsHFb3gcDOcLPBu5Eg1hUHyEwGMsMl3fXoAqpX3D5i0LxMADY40wonf-v/s1600/Img%205%20-%20Sum%20of%20the%20row%20will%20be%20calculated.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sum of the row will be calculated" border="0" data-original-height="247" data-original-width="489" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh5JKLux7q0CljtzZePBJufXLd5BCrCViFVwp7bkC1_iuuy2u9U1rbsAnP2uN02gIhmovnTj9y3vvZgfRR3LX--vf-E2wgoMQwzBxwAX54QExKavlzayMH3BrC0uIEQBKpMsHFb3gcDOcLPBu5Eg1hUHyEwGMsMl3fXoAqpX3D5i0LxMADY40wonf-v/s1600/Img%205%20-%20Sum%20of%20the%20row%20will%20be%20calculated.png"/></a></div>
<p>
Next let’s see how we can apply similar formulas to other rows easily. To do that, first take the mouse pointer to the right bottom corner of the G2 cell. Mouse pointer will change to a + mark. Then drag the mouse upto 10th row while holding down the left mouse button. Then the total for each row will be calculated like this.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhftKLYUWQe2JxROagLhheDDJC6KyYWMw03rHsohzK5dqgCGVuhq3x8kOosgotWUSJG_mMRPny69hNkmzYfnOkYMECbjRvVDn2NS1Z9e7ZSmEnrlyjfDe8eObO8-AMygfaYkulWN9uzLSBZdC9wzZsl2agOkVZwtiodAuC-C2p_z2LkDygfhe_BTblr/s1600/Img%206%20-%20Total%20of%20the%20each%20row%20will%20be%20calcualted.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Total of each row will be calculated" border="0" data-original-height="306" data-original-width="529" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhftKLYUWQe2JxROagLhheDDJC6KyYWMw03rHsohzK5dqgCGVuhq3x8kOosgotWUSJG_mMRPny69hNkmzYfnOkYMECbjRvVDn2NS1Z9e7ZSmEnrlyjfDe8eObO8-AMygfaYkulWN9uzLSBZdC9wzZsl2agOkVZwtiodAuC-C2p_z2LkDygfhe_BTblr/s1600/Img%206%20-%20Total%20of%20the%20each%20row%20will%20be%20calcualted.png"/></a></div>
<p>
You can use this same technique to sum a column as well. Only difference is you need to select a cell bottom to the data set. For an example you can select cell B11.
</p>
<p class="method-number-header">
Method 2
</p>
<p>
Next let’s look at the second method to sum a row in Excel. I will use this sample Excel sheet to explain this second method.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi26kYj7yJipreVJW_XpDW5tEldlFc7fHrFnXv2rv_glz3vnkN19sT3sdxPZTgYOS3P74_wTzbsbEKwXDaha8TB7E5OtdvTtm_QZtjliTEu7rcBIfrazhSfgJrhVvERrb5CvlC1WVioziUbMOvO205l_VcN1LPyrRS0_lpoZ0KNd-dpNwrWqdeHsKup/s1048/Img%207%20-%20Sample%20Excel%20sheet.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample Excel sheet" border="0" width="700" data-original-height="340" data-original-width="1048" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi26kYj7yJipreVJW_XpDW5tEldlFc7fHrFnXv2rv_glz3vnkN19sT3sdxPZTgYOS3P74_wTzbsbEKwXDaha8TB7E5OtdvTtm_QZtjliTEu7rcBIfrazhSfgJrhVvERrb5CvlC1WVioziUbMOvO205l_VcN1LPyrRS0_lpoZ0KNd-dpNwrWqdeHsKup/s600/Img%207%20-%20Sample%20Excel%20sheet.png"/></a></div>
<p>
Suppose we want to get the sum of the 3rd row. If we use this second method we can get the result to any row except row 3. Because if we try to get the result value in the same row then we will get a Circular references error.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJjE5O35gqR4hQaEfHObqATtStse8RDO9d46TuJWBSkqzXymHEXkNb0gb_4W9oEEGB6Gx5Ke-4etpsFVE26jC6hevBWYtuahVdHZ8AQOtwVM4XiZugv2fziPYJrXHgMugJ3rFiw36dYUVfgqY62aAKp2UZXrsE3WeO811G9kIPh963oKLk90x52MHp/s1600/Img%208%20-%20Circular%20references%20error.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Circular references error" border="0" data-original-height="118" data-original-width="719" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJjE5O35gqR4hQaEfHObqATtStse8RDO9d46TuJWBSkqzXymHEXkNb0gb_4W9oEEGB6Gx5Ke-4etpsFVE26jC6hevBWYtuahVdHZ8AQOtwVM4XiZugv2fziPYJrXHgMugJ3rFiw36dYUVfgqY62aAKp2UZXrsE3WeO811G9kIPh963oKLk90x52MHp/s1600/Img%208%20-%20Circular%20references%20error.png"/></a></div>
<p>
To avoid this error let’s get the result in the cell A5. To get the result using the second method enter the following formula in cell A5. Note that you can enter this formula in any cell which is not on row 3.
</p>
<p>
=SUM(3:3)
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgV6Odkf-xXyfCxmsoogw9pGYgc0wqlPP91RvkBu8FBBppRXyaK9Q15J5WYnKoJixoL5jvZyrTZM1G1VB-xcpRU7QxijnSFVxz6UmAI4_IKKgu7_ohDBpifQuvSQhQMHYhqHKa0j52ybYoQ34uZ0NxY1u5GVgJ2-z42rbq2y54YsaDLt-vA-_qiyKLK/s1239/Img%209%20-%20Second%20formula%20to%20sum%20a%20row%20in%20Excel.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Second formula to sum a row in Excel" border="0" width="720" data-original-height="328" data-original-width="1239" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgV6Odkf-xXyfCxmsoogw9pGYgc0wqlPP91RvkBu8FBBppRXyaK9Q15J5WYnKoJixoL5jvZyrTZM1G1VB-xcpRU7QxijnSFVxz6UmAI4_IKKgu7_ohDBpifQuvSQhQMHYhqHKa0j52ybYoQ34uZ0NxY1u5GVgJ2-z42rbq2y54YsaDLt-vA-_qiyKLK/s600/Img%209%20-%20Second%20formula%20to%20sum%20a%20row%20in%20Excel.png"/></a></div>
<p>
Here is the result of the above formula.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6Z3onD8sPRWJhZpJKMjXmq18CjY0mA7q1h2XKNhJ8blmexJmkJjEH3u9ov6VlmapW23W98nWd_C9fhOrDaFF_HduAkC2poLQ4f1P6xrgDBux5uEltekPMuhHcE5sQF2grvWMWnkFgFQ7FnqdhbuRSXxcSbivqEUnMH8vgEpF8VkJ6HfEs9UO3WnJQ/s1065/Img%2010%20-%20Total%20value%20calculated.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Total value calculated" border="0" width="720" data-original-height="177" data-original-width="1065" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6Z3onD8sPRWJhZpJKMjXmq18CjY0mA7q1h2XKNhJ8blmexJmkJjEH3u9ov6VlmapW23W98nWd_C9fhOrDaFF_HduAkC2poLQ4f1P6xrgDBux5uEltekPMuhHcE5sQF2grvWMWnkFgFQ7FnqdhbuRSXxcSbivqEUnMH8vgEpF8VkJ6HfEs9UO3WnJQ/s600/Img%2010%20-%20Total%20value%20calculated.png"/></a></div>
<p>
You can use this method to get the sum of the entire row. Total will be calculated even if you have some text in between.
</p>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEio7E9iQvVTuY0idNuIT74Ch3k-sFwGve2spHqRfnr2GFjet31n6UWbEn8Cd1_61kK2m6G26jjnYsfUCVbSMndoJLhAOmZskcoNQuhNFRhCFpFp9tBW5_3AD_J7QZ4SpadlX9-Zt_vzaw0hAQWenmuQxBfM0x3IOhIxnZ3b-X-2sg8sPbWclq5hfSJw/s855/Img%2011%20-%20Sum%20will%20be%20calculated%20even%20there%20are%20text%20in%20between.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sum will be calculated even there are text in between" border="0" width="700" data-original-height="238" data-original-width="855" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEio7E9iQvVTuY0idNuIT74Ch3k-sFwGve2spHqRfnr2GFjet31n6UWbEn8Cd1_61kK2m6G26jjnYsfUCVbSMndoJLhAOmZskcoNQuhNFRhCFpFp9tBW5_3AD_J7QZ4SpadlX9-Zt_vzaw0hAQWenmuQxBfM0x3IOhIxnZ3b-X-2sg8sPbWclq5hfSJw/s600/Img%2011%20-%20Sum%20will%20be%20calculated%20even%20there%20are%20text%20in%20between.png"/></a></div>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-88978039446801594942022-08-02T09:57:00.000-07:002022-08-02T09:57:27.919-07:00How to Highlight Duplicate Values in Excel<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In this post you will learn about how to highlight duplicate values in Excel. Let’s consider this sample data.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOYrwKb9HCiNbEZmpmy8LzMmnnolxKuLhEQcW1nr1TJDlj8MLorEVsUPXxqUpR7aU3ENMcVtBUsyh7qCo8yLMVe-l_bQX-Q1ZIcXo38Sotuxw_hEvp-gjOgjZqwDu3D1uyy2Lgnp-So9j0Q-Zsjnq9_Rcz5C1KCJCVymE4_-aWT-JM_a_t4iXdz_jZ/s1600/img%201%20-%20sample%20data.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="sample data" border="0" data-original-height="624" data-original-width="449" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOYrwKb9HCiNbEZmpmy8LzMmnnolxKuLhEQcW1nr1TJDlj8MLorEVsUPXxqUpR7aU3ENMcVtBUsyh7qCo8yLMVe-l_bQX-Q1ZIcXo38Sotuxw_hEvp-gjOgjZqwDu3D1uyy2Lgnp-So9j0Q-Zsjnq9_Rcz5C1KCJCVymE4_-aWT-JM_a_t4iXdz_jZ/s1600/img%201%20-%20sample%20data.png"/></a></div>
<br>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
This Excel sheet contains a list of codes in column A. Assume we want to know whether there are duplicated codes in the list and highlight them. Instead of manually examining, we can use conditional formatting available in the Excel application to highlight the duplicates. Follow the below steps.
</p>
<p>
First select the data set.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgagfvTZdgIanNSiM7_2X8zcVFZRiSRdAhQdCKaNrKzvErJnF86A5gMTmXY-JJNkCE1d26e-jckc3fwjaRwGEPHgHTsib3FQq2dUGNDS7PBAnhSKGJR9xhpqVMfFF92khr1h5V7Kg2xRbwAPXlH1MEZp2WeqPh-YcZ53SN5Xit5DXxgB8k8ayVjs_7L/s1600/Img%202%20-%20Select%20the%20data.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select the data" border="0" data-original-height="463" data-original-width="220" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgagfvTZdgIanNSiM7_2X8zcVFZRiSRdAhQdCKaNrKzvErJnF86A5gMTmXY-JJNkCE1d26e-jckc3fwjaRwGEPHgHTsib3FQq2dUGNDS7PBAnhSKGJR9xhpqVMfFF92khr1h5V7Kg2xRbwAPXlH1MEZp2WeqPh-YcZ53SN5Xit5DXxgB8k8ayVjs_7L/s1600/Img%202%20-%20Select%20the%20data.png"/></a></div>
<p>
Then select the “Home” tab from the Excel ribbon.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiK6Fmhzaz1ikaTA9I7ShO9mGfpf_C9Vx_bgmEuyKWy7uK35LeHXjaTsCC-OKIpmuEvFGvaSzQaQlJJnLeEFJwWN5f4zQ0lKVKElcgvyoMizdeX_TSp667wgbzLLbwkaKaQ8T9DUm2wFLpVeqx1fi1mhzBr7sh4RSaYutA3JlUa3PuRjxB86yCMXjx2/s1600/Img%203%20-%20Select%20the%20Home%20tab.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select the Home tab" border="0" data-original-height="193" data-original-width="643" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiK6Fmhzaz1ikaTA9I7ShO9mGfpf_C9Vx_bgmEuyKWy7uK35LeHXjaTsCC-OKIpmuEvFGvaSzQaQlJJnLeEFJwWN5f4zQ0lKVKElcgvyoMizdeX_TSp667wgbzLLbwkaKaQ8T9DUm2wFLpVeqx1fi1mhzBr7sh4RSaYutA3JlUa3PuRjxB86yCMXjx2/s1600/Img%203%20-%20Select%20the%20Home%20tab.png"/></a></div>
<p>
Click on the “Conditional Formatting” in the style group.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjn8qhPyypTUd3xRAH-3wHHFI3kwYVeOBS1Pj33MWfhNCcwFUXSTgb7v5rLSIKXPk4IqQ0dLW56A8Bc0zYNBxEJJhELe7gHjIF_tWZ5bxvIpeB2Lo8l2-qMjDjDC2RMP7nPEbx0nhc6kMhmsZd3XVrx6X8BXOA3MJcOeqQvxY5Bq7aZAeuOOk3UCOFb/s1600/Img%204%20-%20Click%20Conditional%20Formatting.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Click Conditional Formatting" border="0" data-original-height="196" data-original-width="1093" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjn8qhPyypTUd3xRAH-3wHHFI3kwYVeOBS1Pj33MWfhNCcwFUXSTgb7v5rLSIKXPk4IqQ0dLW56A8Bc0zYNBxEJJhELe7gHjIF_tWZ5bxvIpeB2Lo8l2-qMjDjDC2RMP7nPEbx0nhc6kMhmsZd3XVrx6X8BXOA3MJcOeqQvxY5Bq7aZAeuOOk3UCOFb/s1600/Img%204%20-%20Click%20Conditional%20Formatting.png" width="720"/></a></div>
<p>
Now take the cursor on top of the “Highlight Cells Rules” menu. Then a submenu will appear to the right. Click on the “Duplicate Values” from that submenu.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjfcdDJQw49q_wjen3KvJcTu9mTGIm87JdEp3JjyMFeRmTcbEfIGeXQzcb11r_6l09dVc_7wcKG9EWufS00cfm4BE7ki57f1XJy1lJpdc8DAGnOgHyV5xn3dZczBgUNSydvL8vSJa5NVIXpy39UzWbNfezCFUV4lVlPvt5bexck6EdAUaRvidrXa4zr/s1600/Img%205%20-%20Select%20Duplicate%20Values%20from%20submenu.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select Duplicate Values from submenu" border="0" data-original-height="484" data-original-width="558" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjfcdDJQw49q_wjen3KvJcTu9mTGIm87JdEp3JjyMFeRmTcbEfIGeXQzcb11r_6l09dVc_7wcKG9EWufS00cfm4BE7ki57f1XJy1lJpdc8DAGnOgHyV5xn3dZczBgUNSydvL8vSJa5NVIXpy39UzWbNfezCFUV4lVlPvt5bexck6EdAUaRvidrXa4zr/s1600/Img%205%20-%20Select%20Duplicate%20Values%20from%20submenu.png"/></a></div>
<p>
Then the Duplicate values window will open like this. Select “Duplicate” from the first dropdown. I will select “Light Red Fill with Dark Red Text” from the second dropdown. You can select any other format or custom format from the list.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_4EKaEQL6nLnFNtpTeAaOOn5RjLeNakpuKeh2ssIndmW897nyxe-xqYPWDZtxAkHLydQEuYLef0bA_alFDUsJRNRswDa_6j4mvu63TY4eS67Wcm4qnSBO66_icwoCsoT5b8F-RDeEHNmQCUimt0kahDuY6PMB0FoPYebJgcvuk8StynnHidbyBsNB/s1600/Img%206%20-%20Duplicate%20Values%20Window.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Duplicate Values Window" border="0" data-original-height="133" data-original-width="374" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_4EKaEQL6nLnFNtpTeAaOOn5RjLeNakpuKeh2ssIndmW897nyxe-xqYPWDZtxAkHLydQEuYLef0bA_alFDUsJRNRswDa_6j4mvu63TY4eS67Wcm4qnSBO66_icwoCsoT5b8F-RDeEHNmQCUimt0kahDuY6PMB0FoPYebJgcvuk8StynnHidbyBsNB/s1600/Img%206%20-%20Duplicate%20Values%20Window.png"/></a></div>
<p>
Then click the "OK" button. Duplicate codes will be highlighted like this.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjovq1LKucXFwfoEDNctfCy5Bf5QGqEvrb1bWz0KIDXwbVb6Rze0fsf89XOLmz2DMIBzgwP6In0cP-LbWQfQ6b6RE1-aGPRJ2str1PWkSQoIPk6HS3OwhbUqkjHI5vfOQPRHKLheff48ehybd1kXorNmSWR4Ym0LRKDufCfD3EHmSRwlTwx52mbNmgl/s1600/Img%207%20-%20Duplicate%20values%20are%20highlighted.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Duplicate values are highlighted" border="0" data-original-height="448" data-original-width="313" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjovq1LKucXFwfoEDNctfCy5Bf5QGqEvrb1bWz0KIDXwbVb6Rze0fsf89XOLmz2DMIBzgwP6In0cP-LbWQfQ6b6RE1-aGPRJ2str1PWkSQoIPk6HS3OwhbUqkjHI5vfOQPRHKLheff48ehybd1kXorNmSWR4Ym0LRKDufCfD3EHmSRwlTwx52mbNmgl/s1600/Img%207%20-%20Duplicate%20values%20are%20highlighted.png"/></a></div>
<p>
In the above example we selected a range to apply the conditional formatting. However if you need you can add the conditional formatting to the entire column as well. To do that you need to change only one step. When selecting the data, select the entire column instead of the range. Below image shows how you should select the column.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZrKPZiI3-oPcjWxU1iUrufoJcFuWek9Z8dkAv6cK-6d0GfDK7Vt_Excda7t-WPVyii3D5ktL1VaH4vLvbZ2OAr9hVMtHjtmSXzyOSVNejfvZD2y3oZGnE2NRmgy3Uqg3G5lrUfPeWGGHZH1Hbt7-vat6oUMfSgU79IIxiu726dwC6uEbZdE9NdK5J/s1600/Img%208%20-%20Select%20entire%20column.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select entire column" border="0" data-original-height="700" data-original-width="288" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZrKPZiI3-oPcjWxU1iUrufoJcFuWek9Z8dkAv6cK-6d0GfDK7Vt_Excda7t-WPVyii3D5ktL1VaH4vLvbZ2OAr9hVMtHjtmSXzyOSVNejfvZD2y3oZGnE2NRmgy3Uqg3G5lrUfPeWGGHZH1Hbt7-vat6oUMfSgU79IIxiu726dwC6uEbZdE9NdK5J/s1600/Img%208%20-%20Select%20entire%20column.png"/></a></div>
<br>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-29208602269001236292022-06-08T04:35:00.003-07:002022-08-23T22:56:35.708-07:00Select All Cells Using VBA<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In this post you will learn about different ways to select all cells of a worksheet using VBA. When developing VBA macros you may need the VBA program to select all cells of a worksheet. For an example you might need to select all cells before printing the Excel sheet. There are many ways to select all cells of an Excel worksheet using VBA. In this lesson you will learn four different ways to select all cells of an Excel sheet.
</p>
<div class="table-of-contents" style="text-decoration:none;">
<b>Table of contents</b><br>
<a href="#cells_select_method">Select all cells using Cells.Select Method</a><br>
<a href="#used_range_method">Select all cells using UsedRange property</a><br>
<a href="#row_and_col_no_method">Select all cells using last row and column numbers</a><br>
<a href="#current_region_method">Select all cells using CurrentRegion property</a>
</div>
<br><br>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<br><br>
<h4 id="cells_select_method">Cells.Select Method</h4>
<p>
This is the simplest way to select all the cells of an Excel worksheet using VBA. If you want to select all the cells of the activesheet then you can use the below code to do that.
</p>
<div class="vba-code-block">
Sub SelectAllCells_Method1_A()<br><br>
ActiveSheet.Cells.Select<br><br>
End Sub
</div>
<p>
However keep in mind that this method will select all cells of the worksheet including the empty cells.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJR2rmuRe4-GJFmFeFqmUTgtFlMhDeYShu7yOEqFwm_t1yNRGHF-Yii-RE1ZtB41RlMpR4tCYB2-mZ7ova2613pDkurzek51hQMmXifHv2dC97CZFMEGazkGCCgDXosWYu5NJqxow3puoQbVLQIrHTkTDvot6Wf_IqSnvg5C4zDTKOhVMYjWocGz7j/s1600/Pic%201%20-%20All%20the%20cells%20will%20be%20selected%20including%20empty%20cells..png" style="display: block; padding: 1em 0; text-align: center; "><img alt="All the cells will be selected including empty cells. " border="0" data-original-height="701" data-original-width="669" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJR2rmuRe4-GJFmFeFqmUTgtFlMhDeYShu7yOEqFwm_t1yNRGHF-Yii-RE1ZtB41RlMpR4tCYB2-mZ7ova2613pDkurzek51hQMmXifHv2dC97CZFMEGazkGCCgDXosWYu5NJqxow3puoQbVLQIrHTkTDvot6Wf_IqSnvg5C4zDTKOhVMYjWocGz7j/s1600/Pic%201%20-%20All%20the%20cells%20will%20be%20selected%20including%20empty%20cells..png"/></a></div>
<p>
Sometimes you may need to select all cells of a specific sheet of a workbook which contains multiple worksheets. Then you can refer to that specific sheet by its name. If the name of the sheet is “Data” then you can modify the above VBA macro as follows.
</p>
<div class="vba-code-block">
Sub SelectAllCells_Method1_B()<br><br>
Dim WS As Worksheet<br><br>
Set WS = Worksheets("Data")<br><br>
WS.Activate<br>
WS.Cells.Select<br><br>
End Sub
</div>
<p>
Note that it is important to use the Worksheet.Activate method before selecting all cells. Because the VBA program can’t select cells of a worksheet which is not active. Program will throw an error if you try to select cells of a worksheet which is not active.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgMcNJpZcrJjt1k0ExKzm9jBVO7asYrTRE5W01tT-NyREeUWvOIFOIP5HBDQUqTGYOcyScyxB6R1Po3nXt3LijMFSwEooNPTKVu4T-WhftvD3nYCmTv-H-PNK4DkChIcLibProe5VCVoiG9LZs7e9NsCagHIgWTcRmnS-bGaKtAI1U3srBNyTOhGbr/s1600/Pic%202%20-%20Program%20will%20throw%20an%20error%20if%20the%20sheet%20is%20not%20activated.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="VBA Program will throw an error if the sheet is not selected" border="0" data-original-height="212" data-original-width="374" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgMcNJpZcrJjt1k0ExKzm9jBVO7asYrTRE5W01tT-NyREeUWvOIFOIP5HBDQUqTGYOcyScyxB6R1Po3nXt3LijMFSwEooNPTKVu4T-WhftvD3nYCmTv-H-PNK4DkChIcLibProe5VCVoiG9LZs7e9NsCagHIgWTcRmnS-bGaKtAI1U3srBNyTOhGbr/s1600/Pic%202%20-%20Program%20will%20throw%20an%20error%20if%20the%20sheet%20is%20not%20activated.png"/></a></div>
<br>
<h4 id="used_range_method">UsedRange Method</h4>
<p>
Above macros select all the cells of the worksheet. So VBA programs select cells even beyond the last row and column having data. But what if you want to select all the cells only inside the range you have used? For that you can use Worksheet.UsedRange property.
</p>
<div class="vba-code-block">
Sub SelectAllCells_Method2()<br><br>
Dim WS As Worksheet<br><br>
Set WS = Worksheets("Data")<br><br>
WS.Activate<br>
WS.UsedRange.Select<br><br>
End Sub
</div>
<p>
Above VBA code will select all the cells inside the range you have used.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRSoK3I_HC4JpVm0APbhoYPA5Frsd1yB6BZWtfpn9Ngwz6Cy5E9S526Wta_RI1P7t21yWkjK04Vw7Do4QAxUr8-5zl9QpuEefoV-TOqXe1XYugfA38nFSsDDRocugy5edilsfCuH62h5AoR7fnmJZ2gflOv5PPDOkl9fXOVpZEZ7sezZ53y9e-GlKX/s1600/Pic%203%20-%20Select%20all%20the%20cells%20in%20the%20used%20range.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select all the cells in the used range" border="0" data-original-height="701" data-original-width="667" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRSoK3I_HC4JpVm0APbhoYPA5Frsd1yB6BZWtfpn9Ngwz6Cy5E9S526Wta_RI1P7t21yWkjK04Vw7Do4QAxUr8-5zl9QpuEefoV-TOqXe1XYugfA38nFSsDDRocugy5edilsfCuH62h5AoR7fnmJZ2gflOv5PPDOkl9fXOVpZEZ7sezZ53y9e-GlKX/s1600/Pic%203%20-%20Select%20all%20the%20cells%20in%20the%20used%20range.png"/></a></div>
<br>
<h4 id="row_and_col_no_method">Select all cells using last row and column numbers</h4>
<p>
Also there is an alternative way to do this using VBA. First we can find the row number of the bottom most cell having data. Next we can find the column number of the rightmost cell having data. Then we can select the complete range from cell A1 to cell with those last row and column numbers using VBA. Here is how we can do it.
</p>
<div class="vba-code-block">
Sub SelectAllCells_Method3()<br><br>
Dim WS As Worksheet<br>
Dim WS_LastRow As Long<br>
Dim WS_LastColumn As Long<br>
Dim MyRange As Range<br><br>
Set WS = Worksheets("Data")<br><br>
WS_LastRow = WS.Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row<br>
WS_LastColumn = WS.Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column<br><br>
Set MyRange = WS.Range(Cells(1, 1), Cells(WS_LastRow, WS_LastColumn))<br><br>
WS.Activate<br>
MyRange.Select<br><br>
End Sub
</div>
<p>
There is one difference between those last two methods. If you use the last row and column numbers method, the range will be selected from cell A1. But if you use the UsedRange property then the range will be started from the first cell with the data. However you can also modify the last row and column numbers macro to get the same result as the Worksheet.UsedRange property method. But it will be a little more complicated.
</p>
<h4 id="current_region_method">Using CurrentRegion Property</h4>
<p>
We can also use the Range.CurrentRegion property to select all cells of an Excel worksheet. We can easily do that by making a slight change to the UsedRange method. Here is how we can select all cells using the CurrentRegion property.
</p>
<div class="vba-code-block">
Sub SelectAllCells_Method4()<br><br>
Dim WS As Worksheet<br><br>
Set WS = Worksheets("Data")<br><br>
WS.Activate<br>
WS.Range("A1").CurrentRegion.Select<br><br>
End Sub
</div>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
However there is one limitation in this method. If you have empty rows in your worksheet, then the VBA program will select cells only upto that row.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhl0kRDwV4pzaWpOku2uvUyLynpZuIS51KcPXXc3kyEpqX6eaYoOxOBfYdTlHFvAdshTWwV7fZnWhrZgktbFUhzkCwPriKM9ydNP9K32Cvhq4VJCsS6NUWf0gjTaI3-B9ez3fW2O9g0JTmMYjUvQDGYHQ3fMOrJ8yezr9DOf_xTFJvgvU-7tdTbZbRe/s1600/Pic%204%20-%20Limitation%20of%20the%20CurrentRegion%20method.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Limitation of the CurrentRegion method" border="0" data-original-height="679" data-original-width="653" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhl0kRDwV4pzaWpOku2uvUyLynpZuIS51KcPXXc3kyEpqX6eaYoOxOBfYdTlHFvAdshTWwV7fZnWhrZgktbFUhzkCwPriKM9ydNP9K32Cvhq4VJCsS6NUWf0gjTaI3-B9ez3fW2O9g0JTmMYjUvQDGYHQ3fMOrJ8yezr9DOf_xTFJvgvU-7tdTbZbRe/s1600/Pic%204%20-%20Limitation%20of%20the%20CurrentRegion%20method.png"/></a></div>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-69029123581807832112022-03-31T04:24:00.000-07:002022-03-31T04:24:17.192-07:00How to Add or Edit Chart Title Using VBA<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
Typically, If you have titles in your data, Excel will automatically add a relevant title to the chart. But if no titles present in the data or if titles are not selected when inserting the chart, then the created chart will not have a title. And sometimes you might need to add a different title to the chart than present in the data. So in this lesson you will learn how to add or edit a chart title using VBA. Let’s consider this sample chart.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiHAyEVfelBgkZjlHELED6XCuOmWWmqYNzcJDhROaLLSOZszgOVDc2i9fo3KvbQ8ju7fZ0IK3fj0HULft5BB6Sw5e6oEvcFWqya-5FSQrY2xv_QnRffReXQmJ8KmcFn64kFkNYtZbGKzxc5g8WObvtzkyClYAjXAqfmyYXJ0Ap9CBxRZWmwKctvfMF/s1600/Img%201%20-%20Sample%20chart.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample chart" border="0" data-original-height="355" data-original-width="586" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiHAyEVfelBgkZjlHELED6XCuOmWWmqYNzcJDhROaLLSOZszgOVDc2i9fo3KvbQ8ju7fZ0IK3fj0HULft5BB6Sw5e6oEvcFWqya-5FSQrY2xv_QnRffReXQmJ8KmcFn64kFkNYtZbGKzxc5g8WObvtzkyClYAjXAqfmyYXJ0Ap9CBxRZWmwKctvfMF/s1600/Img%201%20-%20Sample%20chart.png"/></a></div>
<br>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
This chart was created from the data below.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiZqstr7CInIikANuDsaTL9yCxMFddUYbrmcZgC-PzfYulFUpWu6MA7qY-tMLAqno68h8qRx6UMycJM8BbZZ7o15g6QWCvWXfxisV7OULkuTuupSvsapE0UNh5R4_pIteUtU-eq_xJ-yStfh_VwmMRW1t9IS2ypZAqgPsBPIh16Xun4OacaFMyKOj2C/s1600/Img%202%20-%20Sample%20data.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample data" border="0" data-original-height="289" data-original-width="289" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiZqstr7CInIikANuDsaTL9yCxMFddUYbrmcZgC-PzfYulFUpWu6MA7qY-tMLAqno68h8qRx6UMycJM8BbZZ7o15g6QWCvWXfxisV7OULkuTuupSvsapE0UNh5R4_pIteUtU-eq_xJ-yStfh_VwmMRW1t9IS2ypZAqgPsBPIh16Xun4OacaFMyKOj2C/s1600/Img%202%20-%20Sample%20data.png"/></a></div>
<p>
If you look at the above Excel line chart, you will notice that the chart was created with the default title text called “Chart Title”. So in this lesson first let’s look at how to edit an existing title like that.
</p>
<p>
Assume you want to edit a title of an active chart. You can do it very easily as shown below.
</p>
<div class="vba-code-block">
Sub EditActiveChartTitle()<br><br>
With ActiveChart<br>
.ChartTitle.Text = "Monthly Sales"<br>
End With<br><br>
End Sub
</div>
<p>
However, for this macro to be worked, your chart should be in an active state(Selected). Otherwise the VBA program will throw an error like this.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBKIvt0RPDAo0vVAyeWFTufX8ybxq5CPfFYW6t7b2TdZin7RSJB07hs90RjUIQxr0s7TJU0YcXBIBzQP7gwMMXlmHxXJrKIcq0WmWcVJCDp9JoN6Us8J76MFDbZeQXzbZjmYc_tq4ODqslwJ3LG9yZkx-l7LJ1bke6yLt1nQwnNpDTXxEWe31zsVRM/s1600/Img%203%20-%20Program%20will%20throw%20an%20errro%20if%20the%20chart%20is%20not%20selected.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Program will throw an error if the chart is not selected" border="0" data-original-height="205" data-original-width="368" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBKIvt0RPDAo0vVAyeWFTufX8ybxq5CPfFYW6t7b2TdZin7RSJB07hs90RjUIQxr0s7TJU0YcXBIBzQP7gwMMXlmHxXJrKIcq0WmWcVJCDp9JoN6Us8J76MFDbZeQXzbZjmYc_tq4ODqslwJ3LG9yZkx-l7LJ1bke6yLt1nQwnNpDTXxEWe31zsVRM/s1600/Img%203%20-%20Program%20will%20throw%20an%20errro%20if%20the%20chart%20is%20not%20selected.png"/></a></div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_jtZYWmcZ9rBtAoLk1caQ3DA-DoUMRwXUjo7eNAOwOfabDVZZOB35dVoE9UKtbZdOjhLPVhp__CDSAnG6HlYBtClaAFio0Pa1ohjBYXzykwzPEgdOL6G8Aqm6ZGUcqEyW9eg8tF3qOZC4sL1hrFJksC2gUpcg3PaQ0c1-uyKts44yVdC21oTQLeGu/s1600/Img%204%20-%20Error%20line.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Error line" border="0" data-original-height="146" data-original-width="441" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_jtZYWmcZ9rBtAoLk1caQ3DA-DoUMRwXUjo7eNAOwOfabDVZZOB35dVoE9UKtbZdOjhLPVhp__CDSAnG6HlYBtClaAFio0Pa1ohjBYXzykwzPEgdOL6G8Aqm6ZGUcqEyW9eg8tF3qOZC4sL1hrFJksC2gUpcg3PaQ0c1-uyKts44yVdC21oTQLeGu/s1600/Img%204%20-%20Error%20line.png"/></a></div>
<p>
But if you know the name of the chart then you can develop a VBA code to edit the title of the chart independent of whether it is active or not. For example, the subroutine below will change the chart title to “Monthly Sales” of a chart called “Chart 2”.
</p>
<div class="vba-code-block">
Sub EditTitleFromChartName()<br><br>
Dim MyChart As Chart<br><br>
Set MyChart = ActiveSheet.Shapes("Chart 2").Chart<br>
With MyChart<br>
.ChartTitle.Text = "Monthly Sales"<br>
End With<br><br>
End Sub
</div>
<p>
Don’t know how to find the name of a chart? Check this post to learn how.<br>
<a href="https://www.excelvbasolutions.com/2020/07/find-name-of-chart-in-excel.html">Find the name of a chart in Excel</a>
</p>
<p>
Sometimes you might need to add a chart title to a chart which doesn’t have any title. Here is an example. This chart doesn’t have any title. As mentioned above this can happen if no titles present in the data or if the user doesn’t select the titles when inserting the chart. So let’s see how we can add a title to it.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiBFZShyE-vxqiU90Nitf6dvvKF_U4IS5W8N1seKKATlfoAGBu0EVc5EyVUOFFFL19pGwWFduiDPYF1dbfHywNTEQmeOXjP5Z_0AxZ0hrF2vFUyIatbB2YmxAKxglWNi13ILXFLUXZVJVkRmytkgUMZ4kQEFielRggk_u8gK_aDSjvnVSgme8lkURTb/s1600/Img%205%20-%20Chart%20without%20a%20title.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Chart without a title" border="0" data-original-height="336" data-original-width="541" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiBFZShyE-vxqiU90Nitf6dvvKF_U4IS5W8N1seKKATlfoAGBu0EVc5EyVUOFFFL19pGwWFduiDPYF1dbfHywNTEQmeOXjP5Z_0AxZ0hrF2vFUyIatbB2YmxAKxglWNi13ILXFLUXZVJVkRmytkgUMZ4kQEFielRggk_u8gK_aDSjvnVSgme8lkURTb/s1600/Img%205%20-%20Chart%20without%20a%20title.png"/></a></div>
<p>
To add a chart title, we need to do a very simple change to the above VBA code we used to edit the title. The only change needed is we should make the HasTitle property from False to True. So this is how you can add a chart title to an active chart by changing the HasTitle property.
</p>
<div class="vba-code-block">
Sub AddChartTitle()<br><br>
With ActiveChart<br>
.HasTitle = True<br>
.ChartTitle.Text = "Monthly Sales"<br>
End With<br><br>
End Sub
</div>
<p>
Also If you know the name of the chart you want to add the title then you can change the above VBA code like this.
</p>
<div class="vba-code-block">
Sub AddTitleFromChartName()<br><br>
Dim MyChart As Chart<br><br>
Set MyChart = ActiveSheet.Shapes("Chart 2").Chart<br>
With MyChart<br>
.HasTitle = True<br>
.ChartTitle.Text = "Monthly Sales"<br>
End With<br><br>
End Sub
</div>
<br>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
Here is the result of the above macros.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCzaiRwbQXqiEy6TVnntqw5A44z-wOZJItrmoQRDUE5V2IX1ZqkhnraXfaXIs9fS5lL36mgS7aijafoZVF6-9ZIx_dQogmDaSm2QvK8xcDSHA5oqXovSlxOP3IHel1BfLbruY0_07s96PCLIxgiqbqhDVcUcyaGTn-RK7tRPcYSqi2cW7tlionPeyg/s1600/Img%206%20-%20VBA%20Macro%20will%20add%20the%20title%20to%20the%20chart.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="VBA Macro will add the title to the chart" border="0" data-original-height="324" data-original-width="534" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCzaiRwbQXqiEy6TVnntqw5A44z-wOZJItrmoQRDUE5V2IX1ZqkhnraXfaXIs9fS5lL36mgS7aijafoZVF6-9ZIx_dQogmDaSm2QvK8xcDSHA5oqXovSlxOP3IHel1BfLbruY0_07s96PCLIxgiqbqhDVcUcyaGTn-RK7tRPcYSqi2cW7tlionPeyg/s1600/Img%206%20-%20VBA%20Macro%20will%20add%20the%20title%20to%20the%20chart.png"/></a></div>
<p>Also Read<br>
<a href="https://www.excelvbasolutions.com/2018/12/how-to-create-line-chart-automatically.html">How to create a line chart automatically - Excel VBA</a><br>
<a href="https://www.excelvbasolutions.com/2021/09/swap-axis-of-excel-chart-without.html">Swap Axis of an Excel Chart Without Changing Excel Sheet Data</a><br>
<a href="https://www.excelvbasolutions.com/2020/07/formatting-excel-line-charts-using-vba.html">Formatting Excel Line Charts Using VBA</a><br>
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-85588640201101741142022-03-25T04:48:00.000-07:002022-03-25T04:48:47.166-07:00How to Insert a Pie Chart Using VBA<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In this lesson you will learn how to insert a pie chart automatically using VBA. Pie charts are very useful in data visualization. Because from a pie chart, users can get a clear picture about the data at a glance. So let's use the below sample data to see how to create a pie chart automatically using VBA. This table shows the profits of different branches of a company.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_8NjAgvYx275zJphzwd7ArfP4c_3hAnhJ_K7Aqd_xPO9pFpYYFB5ygrrPAcUXPJjcLOAgCO9ou44hPIb6UUYHay2Q2IMmDGMc3kjlGiT-Udyn-hepSk1v2xeF47j2gs8gOuoGiqV9QTl6HizATxQswzDGJUhQ8zmbAhzPTr1cDpJlZWdblxfL2ML9/s1600/img%201%20-%20sample%20data%20sheet.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="sample data sheet" border="0" data-original-height="367" data-original-width="300" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_8NjAgvYx275zJphzwd7ArfP4c_3hAnhJ_K7Aqd_xPO9pFpYYFB5ygrrPAcUXPJjcLOAgCO9ou44hPIb6UUYHay2Q2IMmDGMc3kjlGiT-Udyn-hepSk1v2xeF47j2gs8gOuoGiqV9QTl6HizATxQswzDGJUhQ8zmbAhzPTr1cDpJlZWdblxfL2ML9/s1600/img%201%20-%20sample%20data%20sheet.png"/></a></div>
<br>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
Assume name of the worksheet is "Sheet1". As we have data in the range A1:B6, we can insert the pie chart automatically using VBA as follows.
</p>
<div class="vba-code-block">
Sub Create3DPieChart()<br><br>
Dim WS As Worksheet<br><br>
Set WS = Worksheets("Sheet1")<br><br>
WS.Shapes.AddChart2(-1, xl3DPie).Select<br>
ActiveChart.SetSourceData Source:=Range(WS.Name & "!$A$1:$B$6")<br><br>
End Sub
</div>
<p>
Here is the result of the above macro.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgw40LYVSwGJ5l6GANr5adMKcN1hMnRD1FpybfTZh1n4mYm-JLLsng7H1SNMCeVAzrwsJxvt-q5QixfSu8JQylDiFRc6pxChqX3SQfHWccJF7HKheg9z0-q0ZXK752CnvGAaYBj5jPcGzCZWWzO4x_J6QOYzDLoV_2hXANk3S-hkfSdZ7zMkVw5suqZ/s1600/Img%202%20-%20Program%20will%20create%20the%20default%20pie%20chart.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="VBA Program will insert the default pie chart" border="0" data-original-height="350" data-original-width="563" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgw40LYVSwGJ5l6GANr5adMKcN1hMnRD1FpybfTZh1n4mYm-JLLsng7H1SNMCeVAzrwsJxvt-q5QixfSu8JQylDiFRc6pxChqX3SQfHWccJF7HKheg9z0-q0ZXK752CnvGAaYBj5jPcGzCZWWzO4x_J6QOYzDLoV_2hXANk3S-hkfSdZ7zMkVw5suqZ/s1600/Img%202%20-%20Program%20will%20create%20the%20default%20pie%20chart.png"/></a></div>
<p>
This is the syntax of the AddChart2 method.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNbjGQmgjr7_jWFdanSh85wzztQu_h2_73pKnB_12eE5JCvYKg1vQyJtBX-njm_5bjzYdQS2Q9gRUpM7VQecsAsMthIsA9k9c0XL1DaWbIf_hhSTDB5WOL5NEKWHQveiix0HSrveWTANdoZODCOQcuptq38leJLoVMJCDCza2UBzT2Emg7syk8MqAH/s1600/Img%203%20-%20Syntax%20of%20the%20AddChart2%20method.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Syntax of the AddChart2 method" border="0" data-original-height="27" data-original-width="492" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNbjGQmgjr7_jWFdanSh85wzztQu_h2_73pKnB_12eE5JCvYKg1vQyJtBX-njm_5bjzYdQS2Q9gRUpM7VQecsAsMthIsA9k9c0XL1DaWbIf_hhSTDB5WOL5NEKWHQveiix0HSrveWTANdoZODCOQcuptq38leJLoVMJCDCza2UBzT2Emg7syk8MqAH/s1600/Img%203%20-%20Syntax%20of%20the%20AddChart2%20method.png"/></a></div>
<p>
Note that all the parameters are optional for the AddChart2 method. In the above VBA code we have set “-1” as the style and the “xl3DPie” as the xlChartType. Since we have used “-1” Excel will create the default style of the xl3DPie chart type.
</p>
<p>
Check this post if you want to learn more about the AddChart2 method.
</p>
<p>
<a href="https://docs.microsoft.com/en-us/office/vba/api/excel.shapes.addchart2" target="_blank">AddChart2 Method</a>
</p>
<p>
Next let’s see how we can insert a 2D Pie chart by modifying the above VBA code. To do that we need to only change the second parameter of the AddChart2 method.
</p>
<div class="vba-code-block">
Sub Create2DPieChart()<br><br>
Dim WS As Worksheet<br><br>
Set WS = Worksheets("Sheet1")<br><br>
WS.Shapes.AddChart2(-1, xlPie).Select<br>
ActiveChart.SetSourceData Source:=Range(WS.Name & "!$A$1:$B$6")<br><br>
End Sub
</div>
<p>
If you run the above macro, a 2D Pie chart will be created like this.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgaNN8P9rT_dGat_isgooQTO-f4XvrtPcH_mjrfbtAvwpWDlAr58v00AeW_gT_10jDG6jAsNaCpwd4s_gna35nt4OyLnSjO27bwOsUS9XyYkfItWzgIAOT3NwuujPnjRoy3ytpkWvT_fDzuvVaI0lrJaQF44EuPalMu5lb7QdL-Pdn4ixcEh96Atlf9/s1600/Img%205%20-%202D%20Pie%20chart%20created%20by%20the%20macro.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="2D Pie chart inserted by the VBA macro" border="0" data-original-height="294" data-original-width="484" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgaNN8P9rT_dGat_isgooQTO-f4XvrtPcH_mjrfbtAvwpWDlAr58v00AeW_gT_10jDG6jAsNaCpwd4s_gna35nt4OyLnSjO27bwOsUS9XyYkfItWzgIAOT3NwuujPnjRoy3ytpkWvT_fDzuvVaI0lrJaQF44EuPalMu5lb7QdL-Pdn4ixcEh96Atlf9/s1600/Img%205%20-%202D%20Pie%20chart%20created%20by%20the%20macro.png"/></a></div>
<p>
Sometimes you may want to insert a pie chart with a different style. For an example, suppose you want to create a pie chart with a dark background. This is how you can do it in Excel 2013.
</p>
<div class="vba-code-block">
Sub Create3DPieChart_DarkBackground()<br><br>
Dim WS As Worksheet<br><br>
Set WS = Worksheets("Sheet1")<br><br>
WS.Shapes.AddChart2(262, xl3DPie).Select<br>
ActiveChart.SetSourceData Source:=Range(WS.Name & "!$A$1:$B$6")<br><br>
End Sub
</div>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjwQvU4dFXcuxFERt22hajK3BbPDrBtYiPZDP-iep2xu3BQ7wpBlOAPCMITZoYh3h6Qf6xBB_f9G5I6k_j25yNnS4GMTzmZFDVzPLpmwKIljSZOXuPYln-MEA3VQ6pU_P7uknUgGHq0WTvcOA0fh0ftzLTsHtYfmWDMVDtKQajChHJuWsZOBH81vQrJ/s1600/Img%204%20-%20Pie%20chart%20with%20dark%20background.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Pie chart with dark background" border="0" data-original-height="321" data-original-width="521" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjwQvU4dFXcuxFERt22hajK3BbPDrBtYiPZDP-iep2xu3BQ7wpBlOAPCMITZoYh3h6Qf6xBB_f9G5I6k_j25yNnS4GMTzmZFDVzPLpmwKIljSZOXuPYln-MEA3VQ6pU_P7uknUgGHq0WTvcOA0fh0ftzLTsHtYfmWDMVDtKQajChHJuWsZOBH81vQrJ/s1600/Img%204%20-%20Pie%20chart%20with%20dark%20background.png"/></a></div>
<p>
Note that we only changed the style number to create this new chart.
</p>
<p>
However not all the chart styles are available for every Excel version. Because newer Excel versions have more features than previous versions. So how do we find the exact style number of our prefered chart? You can find that by using the Record Macro function.
</p>
<p>
Follow these simple steps to find the style number of your preferred chart.
</p>
<p>
Go to the developer tab and click on Record Macro.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcME3LRbYddtCTFFlUBhrU5tYqj6WFOOnHGj5Zl9FK4i8setCTX67fhzfhZAELd_UDiARhpQpEY4pYuASyN7t7LHNWLh9v4wDZFcA_4cJjRROXB43FPxrFd5BXHL56_yddIvq67PadxFDdZEWnP0GA-qe7CsVkFu4-rUHBCcXUDbiLwZqxCZwrJVZL/s1600/Img%206%20-%20Go%20to%20developer%20tab%20and%20click%20record%20macro.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Go to developer tab and click record macro" border="0" data-original-height="357" data-original-width="670" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcME3LRbYddtCTFFlUBhrU5tYqj6WFOOnHGj5Zl9FK4i8setCTX67fhzfhZAELd_UDiARhpQpEY4pYuASyN7t7LHNWLh9v4wDZFcA_4cJjRROXB43FPxrFd5BXHL56_yddIvq67PadxFDdZEWnP0GA-qe7CsVkFu4-rUHBCcXUDbiLwZqxCZwrJVZL/s1600/Img%206%20-%20Go%20to%20developer%20tab%20and%20click%20record%20macro.png"/></a></div>
<p>
Give the macro a suitable name and click OK. Also you can decide where you want to store the VBA macro by selecting an option from the “Store macro in” dropdown.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj28I29wYOKoUM-ICiKdtg5Gbqomf-W4gFF5M7Hn7ohfVX3eJuRfe9T-u9MmsS1g04XiFupOmlDkkSlnuLZqsl-J3CDjznuzjgBiIfQ1nQKZRxSOePNNQN5WtRgWJdGw3yu8cBVvjEQqUbDyhWK9huQxKshBgX3VLU5enovxAUw1rOk1ZLQwOsUtdSW/s1600/Img%207%20-%20Give%20the%20macro%20a%20name%20and%20click%20OK.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Give the macro a name and click OK" border="0" data-original-height="287" data-original-width="348" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj28I29wYOKoUM-ICiKdtg5Gbqomf-W4gFF5M7Hn7ohfVX3eJuRfe9T-u9MmsS1g04XiFupOmlDkkSlnuLZqsl-J3CDjznuzjgBiIfQ1nQKZRxSOePNNQN5WtRgWJdGw3yu8cBVvjEQqUbDyhWK9huQxKshBgX3VLU5enovxAUw1rOk1ZLQwOsUtdSW/s1600/Img%207%20-%20Give%20the%20macro%20a%20name%20and%20click%20OK.png"/></a></div>
<p>
Then select the data.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPO0m3-UNPvdViZqo_8NJ6pqcdcKDEFGeEUBqKFhE3XvxuMeUgob3GSH-X2Lj-vTSDNO1ZG0Uv0OrVrJI-4l3OfNYFGwkADADDjBm0YhlajhgBvBbYzPC4qmv0Otcgkqp0Ilo4wzXTevzRX8WKF3d51wKMi22CN-Dy7D6GUyVCFDySoC5-hEjqlONN/s1600/Img%208%20-%20Select%20data.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select data" border="0" data-original-height="282" data-original-width="317" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPO0m3-UNPvdViZqo_8NJ6pqcdcKDEFGeEUBqKFhE3XvxuMeUgob3GSH-X2Lj-vTSDNO1ZG0Uv0OrVrJI-4l3OfNYFGwkADADDjBm0YhlajhgBvBbYzPC4qmv0Otcgkqp0Ilo4wzXTevzRX8WKF3d51wKMi22CN-Dy7D6GUyVCFDySoC5-hEjqlONN/s1600/Img%208%20-%20Select%20data.png"/></a></div>
<p>
Go to the Insert tab and select the chart you want to create.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhunYOELHwlJiStDY5VhxC0JYw4Hirf8kGsYQk24m7mpjVl3ZYbDc--SKlQzoi2ZPtnYsLJjAlf8VeqNQcmXA9yRC7Nctea0yQliD5_9TRZiio1PIAfpFSJe7be-IsP7MgshCPCdhh3GabFansgUC2yBRdSxCVk_Qma2p9LTe81cd46FzljANK2hlCd/s926/Img%209%20-%20Select%20the%20chart%20you%20want%20to%20create.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select the chart you want to insert" border="0" width="600" data-original-height="416" data-original-width="926" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhunYOELHwlJiStDY5VhxC0JYw4Hirf8kGsYQk24m7mpjVl3ZYbDc--SKlQzoi2ZPtnYsLJjAlf8VeqNQcmXA9yRC7Nctea0yQliD5_9TRZiio1PIAfpFSJe7be-IsP7MgshCPCdhh3GabFansgUC2yBRdSxCVk_Qma2p9LTe81cd46FzljANK2hlCd/s600/Img%209%20-%20Select%20the%20chart%20you%20want%20to%20create.png"/></a></div>
<p>
Now select a chart design from the list. I will select the 3rd design from the top row for this example.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOJgRD8I41rGR4gfbJJsU8rZPZ7iFymnFP0Ev4E5YdU2W1xqPYOwXeKFB907luAlvvyR1-JqPYlet8-3bCWUumicJ4yRkl7V4F4tRU87WNn9w5FUSvHj3DBi21OnhgMd1DCxzmW-EZkOaaOfizhccv77HqFKZ2sCmHT7BmT3l_QdEa6RZLgj4V3LWm/s994/Img%2010%20-%20Select%20a%20chart%20design%20from%20the%20list.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select a chart design from the list" border="0" width="600" data-original-height="602" data-original-width="994" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOJgRD8I41rGR4gfbJJsU8rZPZ7iFymnFP0Ev4E5YdU2W1xqPYOwXeKFB907luAlvvyR1-JqPYlet8-3bCWUumicJ4yRkl7V4F4tRU87WNn9w5FUSvHj3DBi21OnhgMd1DCxzmW-EZkOaaOfizhccv77HqFKZ2sCmHT7BmT3l_QdEa6RZLgj4V3LWm/s600/Img%2010%20-%20Select%20a%20chart%20design%20from%20the%20list.png"/></a></div>
<p>
Next, go to the “Developer” tab again and click “Stop Recording”.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqK2E8DjEZyK00jjUVVgCHOabvLj_WaRJFgAiKW7o9Kan31RZ_3BVXK1ZMLwUpCQXWLvVjperPGbg4Zi59H7ovkinXJ8Jjr7QQdl1LMEkdh7tSnCdi_xbj8Bts8D723cAwU9gpbcbwXzK3B4Cy7TtiR9L6nC0zyzj_8yOy-WKGwPS-6JfTYovBvKAp/s986/Img%2011%20-%20%20Stop%20recording.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Stop recording" border="0" width="600" data-original-height="610" data-original-width="986" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqK2E8DjEZyK00jjUVVgCHOabvLj_WaRJFgAiKW7o9Kan31RZ_3BVXK1ZMLwUpCQXWLvVjperPGbg4Zi59H7ovkinXJ8Jjr7QQdl1LMEkdh7tSnCdi_xbj8Bts8D723cAwU9gpbcbwXzK3B4Cy7TtiR9L6nC0zyzj_8yOy-WKGwPS-6JfTYovBvKAp/s600/Img%2011%20-%20%20Stop%20recording.png"/></a></div>
<p>
Click on the “Visual Basic” to view the code.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDZKFcdAYHBDb2vyhqKYE6Jk7zzH7LBfKJ6C6d6QOzzvKmKFsld5pLEc8bGqJs-U8GCK2JvmcYP0MZDKKnpg4ohrM-8xsgjfKp90Xtrr6RoKyWlJ5yfQZOrHIRvGSU7NNAqmhaJ1aa5vhEdXeI-MI0jDUF8H2oDr0059LLPAqAJ0Jdb6nWsb1sf6_m/s1600/Img%2012%20-%20Click%20on%20the%20visual%20basic%20to%20view%20the%20code.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Click on the visual basic to view the VBA code" border="0" data-original-height="356" data-original-width="382" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDZKFcdAYHBDb2vyhqKYE6Jk7zzH7LBfKJ6C6d6QOzzvKmKFsld5pLEc8bGqJs-U8GCK2JvmcYP0MZDKKnpg4ohrM-8xsgjfKp90Xtrr6RoKyWlJ5yfQZOrHIRvGSU7NNAqmhaJ1aa5vhEdXeI-MI0jDUF8H2oDr0059LLPAqAJ0Jdb6nWsb1sf6_m/s1600/Img%2012%20-%20Click%20on%20the%20visual%20basic%20to%20view%20the%20code.png"/></a></div>
<br>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
Now you can incorporate these circled values to your code to create a chart automatically with similar style.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgz7cwhJ-FizEpBzAATZeqTMUVKEnTmeDSLZ1lDWeoXGVXdTFMeNQBDt5f-9lCBknWXzfHU9URkN4q6cPIpmhh0u7lurCHblzDcolRBFP20n0j9IKi1H7vX_UTcVtWE_Y9bZGtKJiKcktZR0Z5FzKFusu7R4R7gccYyQSHBDSZVbNmYgTlaZ84J3GMW/s1600/Img%2013%20-%20Generated%20VBA%20code.png" style="display: block; padding: 1em 0; text-align: center; "><img alt="Generated VBA code" border="0" data-original-height="292" data-original-width="576" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgz7cwhJ-FizEpBzAATZeqTMUVKEnTmeDSLZ1lDWeoXGVXdTFMeNQBDt5f-9lCBknWXzfHU9URkN4q6cPIpmhh0u7lurCHblzDcolRBFP20n0j9IKi1H7vX_UTcVtWE_Y9bZGtKJiKcktZR0Z5FzKFusu7R4R7gccYyQSHBDSZVbNmYgTlaZ84J3GMW/s1600/Img%2013%20-%20Generated%20VBA%20code.png"/></a></div>
<p>
Check this post if you want to learn more about recording a macro in Excel.
</p>
<p>
<a href="https://www.excelvbasolutions.com/2020/12/excel-record-macro.html">Record a Macro in Excel
</a>
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-60346930369376544602022-03-01T03:03:00.000-08:002022-03-01T03:03:12.857-08:00VBA - Get Unique Values From Column Into Array
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
When developing Excel VBA programs, sometimes we need to get unique values from a column into an array. Particularly when creating dynamic lists for dropdowns or generating reports. For an example assume you have a dropdown in your VBA program. Suppose that it needs to be updated with the data entered by the user. If the related data is stored in a column, then we can use that column to populate the dropdown. But what, if values are repeated in the column? We don’t show duplicate values in a dropdown list. So then you need to get only unique values to the dropdown. To do that first we can add unique values from column to an array. Then we can easily create the list of the dropdown using that array. So in this lesson you will learn how to populate an array from unique values of a given column. Also I’m going to develop a VBA function for this. So you can readily use it in your VBA programs.
</p>
<p>
Below is the list I’m going to use for this lesson. It is a list of asset ids. And they are listed in column A.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEjioiMijW88i4vRJIij5__YuAsSqV_85hND7t5lhaE8REWBv7r7DvpjSHbbd1mj4uwyVrbd_vSZYvbeSU2fcx_B12XPz7T3YJh8Bn-BgDls-ZXuZIt1FQsL-beimLLkar_44fulVJtzJUq4YGceHXClbTSM2u64TriLukDC4Tm2SceEs5Sg0KxDTc46" style="display: block; padding: 1em 0; text-align: center; "><img alt="List of asset ids" border="0" data-original-height="527" data-original-width="212" src="https://blogger.googleusercontent.com/img/a/AVvXsEjioiMijW88i4vRJIij5__YuAsSqV_85hND7t5lhaE8REWBv7r7DvpjSHbbd1mj4uwyVrbd_vSZYvbeSU2fcx_B12XPz7T3YJh8Bn-BgDls-ZXuZIt1FQsL-beimLLkar_44fulVJtzJUq4YGceHXClbTSM2u64TriLukDC4Tm2SceEs5Sg0KxDTc46"/></a></div>
<br>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
This is not a list of unique values. Because some asset ids are repeated in the column. So now let’s see how we can add only unique values from this column to a VBA array. I’m going to create a custom VBA function for this.
</p>
<div class="vba-code-block">
Function GetUniqueValuesFromColumnIntoArray(WS As Worksheet, ColumnName As String) As String()<br><br>
End Function
</div>
<p>
This VBA function has two parameters. WS and ColumnName. I added these two parameters to input the worksheet name and the column. So you can reuse this for your worksheets easily. Also note that the return type of the VBA function is String(). This is because the function needs to return an array. Want to learn more about returning an array from a VBA function? Check this post.
</p>
<p>
<a href="https://www.excelvbasolutions.com/2022/01/return-array-from-vba-function.html">How to Return an Array From VBA Function</a>
</p>
<p>
Now we have declared the function name with parameters. Next we need to declare a few variables.
</p>
<div class="vba-code-block">
Dim WS_ColumnName_LastRow As Long<br>
Dim i As Long<br>
Dim j As Long<br>
Dim Counter As Long<br>
Dim AllValues() As String<br>
Dim UniqueValues() As String<br>
Dim ValueFound As Boolean<br>
</div>
<p>
AllValues() array will hold all the values from the column. The UniqueValues() variable will hold only the unique values from the column.
</p>
<p>
Next, find the last row of the list.
</p>
<div class="vba-code-block" style="width:95%;">
With WS<br>
WS_ColumnName_LastRow = .Cells(.Rows.Count, ColumnName).End(xlUp).Row<br>
End With
</div>
<p>
Size the “AllValues” dynamic array that has already been formally declared.
</p>
<div class="vba-code-block">
ReDim AllValues(1 To WS_ColumnName_LastRow)
</div>
<p>
Populate the AllValues array using a For Next statement.
</p>
<div class="vba-code-block">
For i = 1 To WS_ColumnName_LastRow<br>
AllValues(i) = WS.Range(ColumnName & i).Value<br>
Next i
</div>
<p>
Then we need to size the UniqueValues array. Here we size the UniqueValues array to the same size of the AllValues array. Because at this moment we don’t know how many unique values we will have in the array. Once all the unique values are populated then we can resize the array to appropriate size.
</p>
<div class="vba-code-block">
ReDim UniqueValues(1 To WS_ColumnName_LastRow)
</div>
<p>
Add the first element from AllValues to the UniqueValues array.
</p>
<div class="vba-code-block">
UniqueValues(1) = AllValues(1)
</div>
<p>
Next we use a nested For Next statement to find unique values.
</p>
<div class="vba-code-block" style="width:95%;">
Counter = 1<br>
For i = 1 To WS_ColumnName_LastRow<br>
ValueFound = False<br>
For j = 1 To Counter<br>
If StrComp(AllValues(i), UniqueValues(j), vbTextCompare) = 0 Then<br>
ValueFound = True<br>
Exit For<br>
End If<br>
Next j<br>
If ValueFound = False Then<br>
Counter = Counter + 1<br>
UniqueValues(Counter) = AllValues(i)<br>
End If<br>
Next i
</div>
<p>
In the above code, the outer For Next statement is used to iterate through the elements of the AllValues array.
</p>
<div class="vba-code-block">
For i = 1 To WS_ColumnName_LastRow <br><br>
Next i
</div>
<p>
Then this inner For Next statement is used to iterate through existing(Newly adding) elements of the UniqueValues array.
</p>
<div class="vba-code-block">
For j = 1 To Counter<br><br>
Next j
</div>
<p>
StrComp function returns 0 if the elements of the two arrays are matching.
</p>
<div class="vba-code-block">
StrComp(AllValues(i), UniqueValues(j), vbTextCompare)
</div>
<p>
Here the variable ValueFound is used as a flag.
</p>
<p>
If the value is not found among the elements of the UniqueValues array, then this new value is added as the next element.
</p>
<div class="vba-code-block">
If ValueFound = False Then<br>
Counter = Counter + 1<br>
UniqueValues(Counter) = AllValues(i)<br>
End If
</div>
<p>
Once all the unique values are collected to the UniqueValues array, we can resize the UniqueValues array as follows. Use the Preserve keyword to keep the existing values while resizing the array. If not, all the values will be erased.
</p>
<div class="vba-code-block">
ReDim Preserve UniqueValues(1 To Counter)
</div>
<p>
Finally, the function returns the UniqueValues array as the output.
</p>
<div class="vba-code-block">
GetUniqueValuesFromColumnIntoArray = UniqueValues
</div>
<p>
And Below is the full code of the function.
</p>
<div class="vba-code-block" style="width:95%;">
Function GetUniqueValuesFromColumnIntoArray(WS As Worksheet, ColumnName As String) As String()<br><br>
Dim WS_ColumnName_LastRow As Long<br>
Dim i As Long<br>
Dim j As Long<br>
Dim Counter As Long<br>
Dim AllValues() As String<br>
Dim UniqueValues() As String<br>
Dim ValueFound As Boolean<br><br>
With WS<br>
WS_ColumnName_LastRow = .Cells(.Rows.Count, ColumnName).End(xlUp).Row<br>
End With<br><br>
ReDim AllValues(1 To WS_ColumnName_LastRow)<br><br>
For i = 1 To WS_ColumnName_LastRow<br>
AllValues(i) = WS.Range(ColumnName & i).Value<br>
Next i<br><br>
ReDim UniqueValues(1 To WS_ColumnName_LastRow)<br>
UniqueValues(1) = AllValues(1)<br>
Counter = 1<br>
For i = 1 To WS_ColumnName_LastRow<br>
ValueFound = False<br>
For j = 1 To Counter<br>
If StrComp(AllValues(i), UniqueValues(j), vbTextCompare) = 0 Then<br>
ValueFound = True<br>
Exit For<br>
End If<br>
Next j<br>
If ValueFound = False Then<br>
Counter = Counter + 1<br>
UniqueValues(Counter) = AllValues(i)<br>
End If<br>
Next i<br><br>
ReDim Preserve UniqueValues(1 To Counter)<br>
GetUniqueValuesFromColumnIntoArray = UniqueValues<br><br>
End Function
</div>
<p>
You can use this function inside a subroutine like this. Assume the name of the worksheet is “Data”.
</p>
<div class="vba-code-block">
Sub Test()<br><br>
Dim WS As Worksheet<br>
Dim UniqueIds() As String<br><br>
Set WS = Worksheets("Data")<br><br>
UniqueIds = GetUniqueValuesFromColumnIntoArray(WS, "A")<br><br>
End Sub
</div>
<p>
Add a breakpoint at “End Sub” and run the program. Then view the UniqueIds array in the “Locals” window.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEglUTNXG8EEEohokB1jsisOjdu4gGMRobMLWBu-vDhmJE20NmXCXDth6UkdMSnJMD1AuQpYiMoRCCQhe3v11jOfxEDt302okD4YzwvyC29-FeiiSxJ5ADXnz_U8c-7q9ijZPrxsXoP0AAW4HtVH7K5-MG8r68VutATssWDYhHnZmc7YOVJ-p8GEH4mL" style="display: block; padding: 1em 0; text-align: center; "><img alt="View the array with unique values" border="0" data-original-height="521" data-original-width="590" src="https://blogger.googleusercontent.com/img/a/AVvXsEglUTNXG8EEEohokB1jsisOjdu4gGMRobMLWBu-vDhmJE20NmXCXDth6UkdMSnJMD1AuQpYiMoRCCQhe3v11jOfxEDt302okD4YzwvyC29-FeiiSxJ5ADXnz_U8c-7q9ijZPrxsXoP0AAW4HtVH7K5-MG8r68VutATssWDYhHnZmc7YOVJ-p8GEH4mL"/></a></div>
<p>
The example worksheet we considered above has a header in row 1. Therefore we have the header “Asset ID” also in the result array. But sometimes you might need to populate unique values into an array without the header. There are few different ways to achieve this. Also you can do it by changing the function or changing the subroutine. In here I will show you how to modify the subroutine to get unique values without the header.
</p>
<p>
Here is how we can modify the subroutine. Once we get the unique values to the array, we can iterate through all the elements using a For Next statement. While loop through the elements we can decrement the index of each and every element by 1. Then the first element which is the header will be removed. Finally we can resize the array to one less than the original size. To keep the current values use the Preserve keyword when resizing.
</p>
<div class="vba-code-block">
Sub Test_2()<br><br>
Dim WS As Worksheet<br>
Dim UniqueIds() As String<br>
Dim i As Long<br><br>
Set WS = Worksheets("Data")<br><br>
UniqueIds = GetUniqueValuesFromColumnIntoArray(WS, "A")<br><br>
For i = 1 To UBound(UniqueIds) - 1<br>
UniqueIds(i) = UniqueIds(i + 1)<br>
Next i<br><br>
ReDim Preserve UniqueIds(1 To UBound(UniqueIds) - 1)<br><br>
End Sub
</div>
<br>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
Below is the outcome of the above subroutine.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEjeHZxhKYf3nhad60ykgjQ86NdXowKxGM3NRXWMv0NgCqcTsCZMKs0CQMimkKoFtHlRxoWV_lre2CK1o1gYvMsPcxatWYbml5r2xaPrrDhVN2BSBBrR94tix5CZoKU7lrbWbAdhL16BUg68Wp5PCXwjGP70mA1pdmburv3yx-CRaS6CxPS8THJ8clwQ" style="display: block; padding: 1em 0; text-align: center; "><img alt="Adding unique values from a column into an array" border="0" data-original-height="589" data-original-width="525" src="https://blogger.googleusercontent.com/img/a/AVvXsEjeHZxhKYf3nhad60ykgjQ86NdXowKxGM3NRXWMv0NgCqcTsCZMKs0CQMimkKoFtHlRxoWV_lre2CK1o1gYvMsPcxatWYbml5r2xaPrrDhVN2BSBBrR94tix5CZoKU7lrbWbAdhL16BUg68Wp5PCXwjGP70mA1pdmburv3yx-CRaS6CxPS8THJ8clwQ"/></a></div>
<p>Also Read<br>
<a href="https://www.excelvbasolutions.com/2022/01/fill-listbox-from-array.html">Fill a Listbox From an Array</a><br>
<a href="https://www.excelvbasolutions.com/2015/10/transposing-array-in-vba.html">Transposing an Array in VBA</a><br>
<a href="https://www.excelvbasolutions.com/2015/10/re-size-dynamic-arrays.html">Re-size Dynamic Arrays</a><br>
<a href="https://www.excelvbasolutions.com/2015/09/quickly-write-multidimensional-array-to.html">Quickly Write Multidimensional Array to Excel Range</a>
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-44029303517312144192022-02-22T05:19:00.003-08:002022-02-22T05:34:28.495-08:00Different Ways to Delete Rows in Excel Sheets<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
When you use Excel for your personal, office or business work, you will often need to delete entire rows from the worksheets. In this lesson you will learn how to delete rows in Excel. There are few different ways to delete rows manually. I will explain them one by one. Let’s consider this sample Excel sheet.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEhvDMh0pgk5Ho71wgfGWDgVQI2Aoed5EakmPkTOxlPpZnCr2cLTiYGdS2xLn33NtgtsIrpNvEc12W2oSiaxYhf74Z-C1b7wi-tKPL5D7IHQhLY7v-fU1-MQiLtFO9vgPS-0_1tGNYjz1GxDaCI4VY2GiyCBnoY91AK2Mht-QUX1xZlPg0QY4nSoVqEu" style="display: block; padding: 1em 0; text-align: center; "><img alt="Sample Excel sheet" border="0" data-original-height="679" data-original-width="643" src="https://blogger.googleusercontent.com/img/a/AVvXsEhvDMh0pgk5Ho71wgfGWDgVQI2Aoed5EakmPkTOxlPpZnCr2cLTiYGdS2xLn33NtgtsIrpNvEc12W2oSiaxYhf74Z-C1b7wi-tKPL5D7IHQhLY7v-fU1-MQiLtFO9vgPS-0_1tGNYjz1GxDaCI4VY2GiyCBnoY91AK2Mht-QUX1xZlPg0QY4nSoVqEu"/></a></div>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
Here is the first method to delete rows manually.
</p>
<p class="method-number-header">
Method 1
</p>
<p>
Right click on a cell of the row you wish to delete. Then select “Delete” from the drop down menu.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEip80s-4_8fr62DbMZoTP_vDGFYiLrt4x-DNF6c2zo169eG2lCy5Idf3WNgbrftl_vTrMoX86b7_kOZ2thsMAzODl2Qn0SWi5HmIZE3zq2ek67LbgXu3ldS17KEDvmY-px0btQhR-8KuBiGiuPGs2WNOzP2XoKaXCK5UElfKN4VDPJUg5Uz4nWKFq_y" style="display: block; padding: 1em 0; text-align: center; "><img alt="Right click and click delete" border="0" data-original-height="541" data-original-width="563" src="https://blogger.googleusercontent.com/img/a/AVvXsEip80s-4_8fr62DbMZoTP_vDGFYiLrt4x-DNF6c2zo169eG2lCy5Idf3WNgbrftl_vTrMoX86b7_kOZ2thsMAzODl2Qn0SWi5HmIZE3zq2ek67LbgXu3ldS17KEDvmY-px0btQhR-8KuBiGiuPGs2WNOzP2XoKaXCK5UElfKN4VDPJUg5Uz4nWKFq_y"/></a></div>
<p>
Then the “Delete” window will appear like this. Select the “Entire row” option button and click OK.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEhYb1f6u3yD1LlPZ6k5tyce-IidxhX-RrS1gRdaUpfe0N09BqX6Gc_djXUu3aRR_ceRmY1-syOgSPrsxcCPsy4_F4K6WwE6_1JVq_ke9UIgxoV493RxamrOsViioXfRfW7jdwMlPFaxvhzSnK63YIxdfvyqMuxlKWJOQuggrvFBz5FcQvuX6mF_-Ysr" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select Entire row and click OK" border="0" data-original-height="358" data-original-width="568" src="https://blogger.googleusercontent.com/img/a/AVvXsEhYb1f6u3yD1LlPZ6k5tyce-IidxhX-RrS1gRdaUpfe0N09BqX6Gc_djXUu3aRR_ceRmY1-syOgSPrsxcCPsy4_F4K6WwE6_1JVq_ke9UIgxoV493RxamrOsViioXfRfW7jdwMlPFaxvhzSnK63YIxdfvyqMuxlKWJOQuggrvFBz5FcQvuX6mF_-Ysr"/></a></div>
<p>
You can also use this method to delete multiple rows as well. First select atleast one cell from each row you want to delete. In this example Excel sheet, I have selected rows 6, 8, 10 and 12. You can use the Ctrl key on your keyboard to select multiple cells. (Press Ctrl key while selecting cells.)
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEgkete_wzbzPvZoYbiBh0aYa4tV9nE811UARNBlQKqzGLfC11-2WiFmdpcUPxETG3uhXfjd8cJxWdYVCXdOwOog0bbNKz7WGtYHQwjWpLWDB4xvIJf0syDfEfymjq1bP_EI2J4g6YwdU1k5pjA_3HyT6I30fvCitNtwzDXT7xrGR-5dSUH8m2P5QmLA" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select atleast one cell from each row you want to delete" border="0" data-original-height="354" data-original-width="579" src="https://blogger.googleusercontent.com/img/a/AVvXsEgkete_wzbzPvZoYbiBh0aYa4tV9nE811UARNBlQKqzGLfC11-2WiFmdpcUPxETG3uhXfjd8cJxWdYVCXdOwOog0bbNKz7WGtYHQwjWpLWDB4xvIJf0syDfEfymjq1bP_EI2J4g6YwdU1k5pjA_3HyT6I30fvCitNtwzDXT7xrGR-5dSUH8m2P5QmLA"/></a></div>
<p>
Now you can follow the same steps you followed to delete one row.
</p>
<p class="method-number-header">
Method 2
</p>
<p>
In this method, first you should take the mouse to the left most side of the Excel sheet. When you take the mouse on top of the row numbers, the mouse pointer will be changed to an arrow like this.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEhvxMH3-vBRxzu1_5bAcwLmZinTxoED7JjC-mdb3OyqNDMR-rs-LdxF4ySCTVmnOhJA5U7MbLEmnDljPrK2DQBJZN2KFuHJdUdeRFn6UbnG6zXlxLiweJOON6hKu3I9kLy9K1kVRoNJxKepofUFQg7gM2THjxxCqNYcm3G7vGqV9oYpWweG37p_Y1Df" style="display: block; padding: 1em 0; text-align: center; "><img alt="Take cursor to the top of the row number you want to delete" border="0" data-original-height="256" data-original-width="426" src="https://blogger.googleusercontent.com/img/a/AVvXsEhvxMH3-vBRxzu1_5bAcwLmZinTxoED7JjC-mdb3OyqNDMR-rs-LdxF4ySCTVmnOhJA5U7MbLEmnDljPrK2DQBJZN2KFuHJdUdeRFn6UbnG6zXlxLiweJOON6hKu3I9kLy9K1kVRoNJxKepofUFQg7gM2THjxxCqNYcm3G7vGqV9oYpWweG37p_Y1Df"/></a></div>
<p>
Now click the right mouse button. Select “Delete” from the menu. Row will be deleted instantly.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEjmpzrSuQUDrVsYatdOgb91xD4zb4L2H9s49gPCuvhlRWIe8QL3wsB2qsoLiAYcS9WyHCOWifwzZDcvxYP0UilxQwUO5hWVlE7Aj2QUgHiw03SPJb4FFzGsfhdKRwlxm3aPgN1sgOgds7J9YB5FnMCtwfmBY-qtRV2xD-Wc1GjQE98Kp3yFrS2tzkRa" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select Delete from the dropdown menu" border="0" data-original-height="464" data-original-width="665" src="https://blogger.googleusercontent.com/img/a/AVvXsEjmpzrSuQUDrVsYatdOgb91xD4zb4L2H9s49gPCuvhlRWIe8QL3wsB2qsoLiAYcS9WyHCOWifwzZDcvxYP0UilxQwUO5hWVlE7Aj2QUgHiw03SPJb4FFzGsfhdKRwlxm3aPgN1sgOgds7J9YB5FnMCtwfmBY-qtRV2xD-Wc1GjQE98Kp3yFrS2tzkRa"/></a></div>
<p>
Likewise you can use this method to delete multiple rows in Excel sheets. First select the rows you want to delete. You can use the Ctrl key on your keyboard to select multiple rows.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEgDHaeYRZ_0i_o_uKHj79HQdokEytz-LQvWA6mPHKDrUUcC2MUQM9YfRlvLRDuLO3-MDI4_Xm_isdZ6TYOC3Or0daqZ5HSAIfkoK-0uiY9lFNZ6Dv9Qyx0wzYk7jsriBUdH4YKy4f7M4aem9wogtRcm-AWPuiAtAlSQVgbD7HWfiegvqBOo1XUmn_RW" style="display: block; padding: 1em 0; text-align: center; "><img alt="Select multiple rows" border="0" data-original-height="315" data-original-width="668" src="https://blogger.googleusercontent.com/img/a/AVvXsEgDHaeYRZ_0i_o_uKHj79HQdokEytz-LQvWA6mPHKDrUUcC2MUQM9YfRlvLRDuLO3-MDI4_Xm_isdZ6TYOC3Or0daqZ5HSAIfkoK-0uiY9lFNZ6Dv9Qyx0wzYk7jsriBUdH4YKy4f7M4aem9wogtRcm-AWPuiAtAlSQVgbD7HWfiegvqBOo1XUmn_RW"/></a></div>
<p>
Once you select the rows, you can follow the same steps followed to delete a single row.
</p>
<p>
Sometimes we may need to delete a set of adjacent rows in Excel. This video shows how to select a set of contiguous cells easily and then delete the entire rows.
</p>
<div class="separator" style="clear: both; text-align: center;"><iframe allowfullscreen='allowfullscreen' webkitallowfullscreen='webkitallowfullscreen' mozallowfullscreen='mozallowfullscreen' width='600' height='498' src='https://www.blogger.com/video.g?token=AD6v5dzqZBZYz6tMg8W0HbdXHTQ3FrEag9lMp4sWSDZ4yJw_FDz2rcTRxKxAusu2eyJM_Oo5UJpuf63Jd2ZvOl-L4w' class='b-hbp-video b-uploaded' frameborder='0'></iframe></div>
<br><br>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
Here is also an alternative way to delete a set of adjoining rows.
</p>
<div class="separator" style="clear: both; text-align: center;"><iframe allowfullscreen='allowfullscreen' webkitallowfullscreen='webkitallowfullscreen' mozallowfullscreen='mozallowfullscreen' width='600' height='498' src='https://www.blogger.com/video.g?token=AD6v5dxwyHn8T-uRSzZGU47sL9LREwp7016LYFwmMREkn3Hq2jaCXWndErs8c1_XrxCCjpDux_afXprSXD7V-mnCfg' class='b-hbp-video b-uploaded' frameborder='0'></iframe></div>
<p>
<b>Also read</b><br>
<a href="https://www.excelvbasolutions.com/2018/05/how-to-read-write-delete-and-move-excel.html">How to Read, Write, Delete and Move excel comments</a><br>
<a href="https://www.excelvbasolutions.com/2020/12/excel-record-macro.html">Record a Macro in Excel</a><br>
<a href="https://www.excelvbasolutions.com/2021/11/clear-excel-sheet-contents-except-first-row-vba.html">Clear Contents of Excel Sheet Except First Row Using VBA</a><br>
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0tag:blogger.com,1999:blog-2870118127245011700.post-36912576414477490472022-02-14T09:30:00.001-08:002022-02-14T09:30:46.752-08:00How to Pass an Array to a VBA Function<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-104452989-1', 'auto');
ga('send', 'pageview');
</script>
<p>
In this lesson you will learn how to pass an array to a VBA function. You can’t pass an array to any type of function. Function should be developed in such a way that it can accept arrays as variables. Syntax is similar to functions which accept other types of variables. But array arguments should have parenthesis at the end of the name. Here is the syntax of a VBA function which accepts an array as an argument. Data type of the argument is string. So you can only pass an array of a type string to this function.
</p>
<div class="vba-code-block">
Function FunctionName(ArrayParameterName() As String)<br><br>
'-----------------------<br>
'Codes of the function<br>
'-----------------------<br><br>
FunctionName = ResultString<br><br>
End Function
</div>
<br>
<div align="center">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- In post ad top -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="4352655930"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<p>
Above example shows the syntax of a VBA function which has one argument. It accepts only arrays as the argument. Now let’s look at how to create a function using that syntax. Let’s develop a VBA function to calculate the average marks of students. It will accept an array of type double as the argument. This is how we can do it.
</p>
<div class="vba-code-block">
Function AverageMarks(Marks() As Integer) As Double<br><br>
Dim TotalMarks As Integer<br>
Dim StudentCount As Integer<br>
Dim i As Integer<br><br>
For i = LBound(Marks) To UBound(Marks)<br>
TotalMarks = TotalMarks + Marks(i)<br>
StudentCount = StudentCount + 1<br>
Next i<br><br>
AverageMarks = TotalMarks / StudentCount<br><br>
End Function
</div>
<p>
Function iterates through elements of the “Marks” array while calculating the total marks and the student count. Finally calculate the average marks by dividing total marks by the student count.
We can call this within a subroutine as follows.
</p>
<div class="vba-code-block">
Sub FindAverageMarksOfClass()<br><br>
Dim StudentMarks(9) As Integer<br>
Dim ClassAvg As Double<br><br>
StudentMarks(0) = 52<br>
StudentMarks(1) = 92<br>
StudentMarks(2) = 85<br>
StudentMarks(3) = 45<br>
StudentMarks(4) = 65<br>
StudentMarks(5) = 32<br>
StudentMarks(6) = 28<br>
StudentMarks(7) = 62<br>
StudentMarks(8) = 70<br>
StudentMarks(9) = 68<br><br>
ClassAvg = AverageMarks(StudentMarks())<br><br>
MsgBox ClassAvg<br><br>
End Sub
</div>
<p>
This is the result of the subroutine.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEg2VaEohiEPGGMqahpOPH9u0iwNy0sJyafRX3-TEH9Ol9UivvO5C5GycFxi77tvEGnFwizTcGirApcpqj8vr6t8_ImeDHq2HGMEos6BZsk_s9Uc1RfDTc5nN6UY0cB8wzdyMqAjqu4-l2lPCpdTKYB82p2j7qlcf91_SWrxGipKS-jXAwjHjfae_Nrm" style="display: block; padding: 1em 0; text-align: center; "><img alt="Return value of the function" border="0" data-original-height="188" data-original-width="221" src="https://blogger.googleusercontent.com/img/a/AVvXsEg2VaEohiEPGGMqahpOPH9u0iwNy0sJyafRX3-TEH9Ol9UivvO5C5GycFxi77tvEGnFwizTcGirApcpqj8vr6t8_ImeDHq2HGMEos6BZsk_s9Uc1RfDTc5nN6UY0cB8wzdyMqAjqu4-l2lPCpdTKYB82p2j7qlcf91_SWrxGipKS-jXAwjHjfae_Nrm"/></a></div>
<p>
Note that we have parentheses for the argument of the function.
</p>
<div class="vba-code-block">
Function AverageMarks(Marks() As Integer) As Double
</div>
<p>
However we can omit the parentheses when calling the function. So both the below methods will work.
</p>
<div class="vba-code-block">
ClassAvg = AverageMarks(StudentMarks())
</div>
<br><br>
<div class="vba-code-block">
ClassAvg = AverageMarks(StudentMarks)
</div>
<p>
What will happen if we pass non-array to a function which accepts array as the argument. Let’s check this by passing a non-array to the above function. Note that our VBA function has an argument of data type “Integer”. So we are going to pass a value of the same data type.
</p>
<div class="vba-code-block">
Sub FindAverageMarksOfOneStudent()<br><br>
Dim Student1_Marks As Integer<br>
Dim ClassAvg As Double<br><br>
Student1_Marks = 85<br><br>
ClassAvg = AverageMarks(Student1_Marks)<br><br>
MsgBox ClassAvg<br><br>
End Sub
</div>
<p>
Above subroutine has a variable called “Student1_Marks”. It is a non-array variable of type integer. We assigned the marks of one student to that variable. Then called the function “AverageMarks” using the “Student1_Marks” as the parameter. Here is the outcome.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEg8CQ3pDQLSiktAgxY7TSDkaziLLDYJ8dpIfmY4Tr4MNvKOtPi2eyyhNOConI0EsMRKlEKEHgmlxMpotnvLka8RDW5RrLuEPqbUURHpW1EUmJABxILDEqR_fDsWc3JRYMOqpaAfpJ0ado1_1QZlvevA0iPfjs91clu_1kmkRMo3_4KZi5PwneyqApfY" style="display: block; padding: 1em 0; text-align: center; "><img alt="Get compile error if you pass non-array to a function which requires an array as argument" border="0" data-original-height="249" data-original-width="506" src="https://blogger.googleusercontent.com/img/a/AVvXsEg8CQ3pDQLSiktAgxY7TSDkaziLLDYJ8dpIfmY4Tr4MNvKOtPi2eyyhNOConI0EsMRKlEKEHgmlxMpotnvLka8RDW5RrLuEPqbUURHpW1EUmJABxILDEqR_fDsWc3JRYMOqpaAfpJ0ado1_1QZlvevA0iPfjs91clu_1kmkRMo3_4KZi5PwneyqApfY"/></a></div>
<p>
So you will get a compile error if you pass a non-array to a function which accepts an array as the argument.
</p>
<p>
Also you can pass an array to function only as ByRef (by reference). Some functions may analyze the array and return a result without doing any change to the array. But some VBA functions make changes to the array as well. So if the called function does any changes to the array, changes affect the original array. I will explain this using an example.
</p>
<p>
Assume we want a function which returns the third power of given numbers.
</p>
<div class="vba-code-block">
Function ThirdPower(Arr() As Long) As Long()<br><br>
Dim i As Integer<br><br>
For i = LBound(Arr) To UBound(Arr)<br>
Arr(i) = Arr(i) ^ 3<br>
Next i<br><br>
ThirdPower = Arr<br><br>
End Function
</div>
<p>
We can pass numbers as an array. Then the function will return the third power of those numbers. Here is how we can call this function from a subroutine.
</p>
<div class="vba-code-block">
Sub TestMacro1()<br><br>
Dim MyArr(1 To 5) As Long<br>
Dim ResultArr() As Long<br><br>
MyArr(1) = 2<br>
MyArr(2) = 3<br>
MyArr(3) = 7<br>
MyArr(4) = 8<br>
MyArr(5) = 10<br><br>
ResultArr = ThirdPower(MyArr())<br><br>
End Sub
</div>
<p>
Now let’s set a breakpoint at “End Sub” and run the code.
</p>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEhZtF9UnqL0kqo2kchWcwGw6pxyFYxFLVrn49kW-kgcprPxzxJxPk0dGc8nXD3Jg3OHTzKMZQhdb3G4I1tqkMq98FX-l72kZh2yKdt56MJaySR8_tsGgxhtKv_DsUPsx95crqFGkdrYjds7Y3ei0C-Eys7nAWmKioauJ51mz-CGUHkFBvSagMrLa3XZ" style="display: block; padding: 1em 0; text-align: center; "><img alt="Original array is changed when passed to the function" border="0" data-original-height="637" data-original-width="545" src="https://blogger.googleusercontent.com/img/a/AVvXsEhZtF9UnqL0kqo2kchWcwGw6pxyFYxFLVrn49kW-kgcprPxzxJxPk0dGc8nXD3Jg3OHTzKMZQhdb3G4I1tqkMq98FX-l72kZh2yKdt56MJaySR8_tsGgxhtKv_DsUPsx95crqFGkdrYjds7Y3ei0C-Eys7nAWmKioauJ51mz-CGUHkFBvSagMrLa3XZ"/></a></div>
<p>
If you view the arrays in the locals window, you will notice that the “MyArr” is also updated with the third power values. This is because the array is passed to the function by reference. You might think that you can pass the array by value using the ByVal statement. But it is impossible. You will get a syntax error if you try to pass the array by value.
</p>
<div align="center">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- vbadevelopers_sidebar-right-1_AdSense2_336x280_as -->
<ins class="adsbygoogle"
style="display:inline-block;width:336px;height:280px"
data-ad-client="ca-pub-5010859783292837"
data-ad-slot="5338838703"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<br>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEjX794KMLFKDQsey3j5MOSj9bC0-UB2i9JazAtozXR6JKy2hBWdfchBE0zQvux-i0lJDIr-aHW677_WrTI10SUT6NFh8F0UCxdQde0MCxncQrdmNUG3eHtgZ0dGGpKQpNfjmRRq_e9gZ076Et8GOTYhzswokBFYNUf4h82EXjB2X64MlSLF1l0FH3ab" style="display: block; padding: 1em 0; text-align: center; "><img alt="Can not pass an array to a function by value" border="0" data-original-height="223" data-original-width="605" src="https://blogger.googleusercontent.com/img/a/AVvXsEjX794KMLFKDQsey3j5MOSj9bC0-UB2i9JazAtozXR6JKy2hBWdfchBE0zQvux-i0lJDIr-aHW677_WrTI10SUT6NFh8F0UCxdQde0MCxncQrdmNUG3eHtgZ0dGGpKQpNfjmRRq_e9gZ076Et8GOTYhzswokBFYNUf4h82EXjB2X64MlSLF1l0FH3ab"/></a></div>
<p>
<b>Also read</b><br>
<a href="https://www.excelvbasolutions.com/2022/01/return-array-from-vba-function.html">How to Return an Array From VBA Function
</a><br>
<a href="https://www.excelvbasolutions.com/2015/07/fixed-size-arrays-in-vba.html">Fixed Size Arrays in VBA</a><br>
<a href="https://www.excelvbasolutions.com/2015/08/multidimensional-arrays-in-vba.html">Multidimensional Arrays in VBA</a><br>
<a href="https://www.excelvbasolutions.com/2015/08/dynamic-arrays-in-vba.html">Dynamic arrays in VBA</a><br>
<a href="https://www.excelvbasolutions.com/2015/09/quickly-write-multidimensional-array-to.html">Quickly Write Multidimensional Array to Excel Range
</a><br>
</p>
Roshantha De Melhttp://www.blogger.com/profile/11350883142555417861noreply@blogger.com0