<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ visual basic - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ visual basic - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 13 May 2026 22:45:09 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/visual-basic/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Learn Visual Basic (.NET) – Full Course ]]>
                </title>
                <description>
                    <![CDATA[ Did you know that Visual Basic is currently a more popular programming language than JavaScript? That is according to the TIOBE index, which is one of the most respected indicators of the popularity of programming languages. Visual Basic is an object... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-visual-basic-net-full-course/</link>
                <guid isPermaLink="false">66b2056508bc664c3c097ee7</guid>
                
                    <category>
                        <![CDATA[ visual basic ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Fri, 17 Jun 2022 14:24:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/maxresdefault.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Did you know that Visual Basic is currently a more popular programming language than JavaScript? That is according to <a target="_blank" href="https://www.tiobe.com/tiobe-index/">the TIOBE index</a>, which is one of the most respected indicators of the popularity of programming languages.</p>
<p>Visual Basic is an object-oriented programming language developed by Microsoft. It makes it fast and easy to create type-safe .NET apps. Some common uses for Visual Basic are creating Windows-based applications, utilities to perform specific tasks, and adding functionality to existing applications.</p>
<p>We just published a full visual basic course for beginners on the freeCodeCamp.org YouTube channel.</p>
<p>Kevin Drumm created this course. Kevin is the head of computer science at a school in the UK. He has also created hundreds of programming tutorials.</p>
<p>In this course you will learn about the basic constructs of high level programming languages, including sequence, selection and iteration. You will learn how to build an event-driven, form-based, user interface to capture input, and you will learn how to write code to validate and process the data collected. </p>
<p>Here are the sections in this course:</p>
<ul>
<li>Hello Visual Studio</li>
<li>Customise The Visual Studio IDE</li>
<li>Output and Variables</li>
<li>Variable Data Types</li>
<li>Input with Windows Forms</li>
<li>Debugging Code</li>
<li>Arithmetic Operators</li>
<li>Complex Arithmetic Expressions</li>
<li>Selection with If Statements</li>
<li>Logical and Relational Operators 1</li>
<li>Logical and Relational Operators 2</li>
<li>Select Case</li>
<li>For Next</li>
<li>Practice For Next Loops &amp; If Blocks</li>
<li>Do While</li>
<li>Condition Controlled Loops</li>
<li>Array Variables</li>
<li>Practice Arrays &amp; Loops</li>
<li>Linear Search</li>
<li>Two Dimensional Arrays</li>
<li>2D Arrays &amp; Nested Loops</li>
</ul>
<p>Watch the full course below or <a target="_blank" href="https://youtu.be/HFWQdGn5DaU">on the freeCodeCamp.org YouTube channel</a> (3-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/HFWQdGn5DaU" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Visual Basic Excel Tutorial – How to Automate Repetitive Tasks in a Spreadsheet ]]>
                </title>
                <description>
                    <![CDATA[ By Sander Vreeken I use VBA, or Visual Basic for Applications, to automate my repetitive tasks. This saves me quite a lot of time in my day-to-day life.  Based on the fact that you're reading this tutorial, I assume that you would like to be able to ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/automate-repetitive-tasks-in-excel-with-vba/</link>
                <guid isPermaLink="false">66d460ee23b027d0ff16f2c8</guid>
                
                    <category>
                        <![CDATA[ automation ]]>
                    </category>
                
                    <category>
                        <![CDATA[ excel ]]>
                    </category>
                
                    <category>
                        <![CDATA[ visual basic ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 29 Jul 2021 15:35:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/07/Thumbnail2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sander Vreeken</p>
<p>I use VBA, or Visual Basic for Applications, to automate my repetitive tasks. This saves me quite a lot of time in my day-to-day life. </p>
<p>Based on the fact that you're reading this tutorial, I assume that you would like to be able to do the same.</p>
<p>So I will take you through the basics of VBA, such as how to use variables, loops, if-else statements, arrays, and dictionaries.</p>
<h2 id="heading-intro-to-vba-and-overview-of-the-project">Intro to VBA and Overview of the Project</h2>
<p>Although VBA was declared legacy in 2008, this implementation of Visual Basic can help you automate the repetitive tasks in your daily life.</p>
<p>The language is object oriented, it's written in C++, and it includes all the features you would expect in a coding language these days.</p>
<p>In this tutorial we will be writing a macro that prepares a template to note the temperatures in several European cities – Amsterdam, Barcelona, Berlin, Brussels, London, and Rome. </p>
<p>The template will be automatically created by a macro we build together based on the cities and date that we use as parameters. </p>
<p>Finally, we will also learn how to import the data from another file in our template.</p>
<p>In order to follow along with this tutorial, I expect you to have a basic understanding of Excel. But you don't need any experience with VBA (although it might help you understand the different concepts I'll introduce).</p>
<p>I have downloaded <a target="_blank" href="https://www.meteoblue.com/">several Excel files of data</a> which are free to use. You can also <a target="_blank" href="https://github.com/SanderVreeken/FreeCodeCamp-VBA-Automation">find them on my GitHub</a> together with the final result.</p>
<h2 id="heading-lets-define-our-parameters">Let's Define Our Parameters</h2>
<p>First we will define the different cities that we will be using for this tutorial. If we were to do this manually, increasing the number of cities would consequently mean more work. </p>
<p>But in our case, since the macro will do the work for us, we can add as many cities as we like. Then we'll just run the macro and go do something else.</p>
<p>In order to define the cities, we can do one of two things. Either we can include the cities in an array in the code, or we can define them in a separate worksheet in our template. </p>
<p>For this tutorial, we'll be doing the latter, which makes it easier for other people to add cities later on without any knowledge of VBA.</p>
<h3 id="heading-how-to-set-up-the-excel-workbook">How to Set Up the Excel Workbook</h3>
<p>Open a new Excel file, save it as Excel Macro-Enabled Workbook (extension .xlsm), and name it whatever you like. </p>
<p>Rename the first worksheet to Cities and add the six cities by typing their names in the first column with a city on every row, as shown here:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-83.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 01: Cities Worksheet</em></p>
<p>To define the date, we will create another worksheet called Date where the user can define the month they want the template to be created for. </p>
<p>Since not every year and month are the same (for example different number of days, different number of weekdays), the template for your data needs to be adjusted every single month in order to correctly show these differences. </p>
<p>I have also added data validation to make sure we can only enter a date and to make sure it's a date not beyond today's date (but this is completely optional). As long as you have a cell with a date, preferably cell B1, that is enough.</p>
<p>For this tutorial, we'll only need the month and year, so I have chosen a different date format as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-89.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 02: Date Worksheet</em></p>
<h2 id="heading-how-to-build-a-macro-with-visual-basic-for-applications">How to Build a Macro with Visual Basic for Applications</h2>
<p>Now that we have set the parameters, we can move on with actually building the macro. </p>
<p>If this is the first time you are using VBA, you might need to customize your ribbon to get the necessary functions available. </p>
<p>In order to do so, make sure that the Developer box is ticked (as shown in Figure 3 below) and that the Developer options are available in your ribbon after you have saved your changes.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-85.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 03: Settings Excel</em></p>
<p>You should now be able to open Visual Basic from the Developer tab in Excel, which should look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-86.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 04: Visual Basic</em></p>
<p>This is the editor provided by Excel where you will be able to create, adjust, and remove your functions and macros. I will not go into too much detail for now, but I'll just explain some of the elements as we go. </p>
<p>Now, let's got our hands dirty and write our first macro.   </p>
<p>You could choose to write macros for a single worksheet only, or choose to have them available in the entire workbook. </p>
<p>As the two worksheets we created earlier only maintain the parameters, I chose to write the macros for the entire workbook by double-clicking the "ThisWorkbook" option in the sidebar for our project. </p>
<p><em>Don't worry about the PERSONAL.xlsb in my screenshot for now – this is a file containing functions that I can use in all my files and will be handled in a future tutorial.</em></p>
<h3 id="heading-how-to-create-our-first-macro">How to Create Our First Macro</h3>
<p>After you've selected the workbook, you are ready to start your first program.</p>
<p>Macros in VBA start with the keyword Sub, short for subroutine, followed by their name and two parentheses. Although the editor is nothing compared to an IDE like Visual Studio Code, it will complete the code with End Sub when you hit enter after the two parentheses. </p>
<p>For now, I have created an empty macro called <code>CreateTemplate</code> which looks like this:</p>
<pre><code class="lang-vba">Sub CreateTemplate()

End Sub
</code></pre>
<p>It is a bit sad that the function does not do anything for now, so let's add the following code and find out what it does:</p>
<pre><code class="lang-vba">Sub CreateTemplate()

    'Adding a new worksheet called NewSheet to the workbook, next to the worksheet we currently have selected.
    Sheets.Add.Name = "NewSheet"

End Sub
</code></pre>
<p>If we were to run this code right now, the function would create a new worksheet in our Excel workbook called NewSheet. </p>
<p>Note that I have included a comment in the code by starting the line with an apostrophe. This will not be executed, but is only there to help you and myself understand the code. </p>
<p>We can run this code by placing our cursor somewhere in the function and pressing the green 'play' icon on top of the editor, which says Run Sub when you hover over it. </p>
<p>After you have pressed this button, you will see that new worksheet called NewSheet has been created in our workbook and has also been added in the sidebar, next to the sheets we already had.</p>
<p>Personally, I do not like the fact that the sheet is created next to the sheet we had (maybe on purpose, maybe not) selected. Therefore, I will add a parameter to the add method to define its location:</p>
<pre><code class="lang-vba">Sub CreateTemplate()

    'Adding a new worksheet called NewSheet to the workbook, next to the worksheet Date.
    Sheets.Add(After:=Sheets("Date")).Name = "NewSheet"

End Sub
</code></pre>
<p>Delete the newly created sheet, as we will now create the worksheets for every city we defined earlier. As the number of cities entered might differ, we want to know how many rows are actually being used in our Cities worksheet.</p>
<pre><code class="lang-vba">Sub CreateTemplate()

    Debug.Print Worksheets("Cities").UsedRange.Rows.Count

End Sub
</code></pre>
<p>To test whether we are able to extract the date from the file, we use <code>Debug.Print</code> (similar to print in Python or console.log in JavaScript) to print the numbers of rows, which Excel will calculate for us based on the code we provided.</p>
<p>Make sure to open your Immediate Window (in Visual Basic, by selecting View &gt; Immediate Window) and run the macro above. It will print six, just like we expect, after we have defined the same number of cities in our Cities worksheet earlier in this tutorial.</p>
<h2 id="heading-how-to-store-values-as-variables-in-vba">How to Store Values as Variables in VBA</h2>
<p>Rather than printing this value, I want to store it as a variable instead. To do so, add the following code:</p>
<pre><code class="lang-vba">Sub CreateTemplate()
    'Variable that will contain the number of cities.
    Dim NumberOfCities As Integer

    NumberOfCities = Worksheets("Cities").UsedRange.Rows.Count
    Debug.Print NumberOfCities

End Sub
</code></pre>
<p>We use the Dim keyword in VBA to declare a variable, which should always include the type (for example String, Integer, Double). </p>
<p>After we've declared our variable, we can assign the number of rows used, as printed before, to this variable and print the number to test that we get the same result. You can see this in the image below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-90.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 05: Printing to Immediate Window</em></p>
<p>We can now use this number to define a loop that will create a sheet for every city.</p>
<pre><code class="lang-vba">Sub CreateTemplate()
    'Variable that will contain the cityname that is used to name a sheet.
    Dim CityName As String
    'Variable that will contain the number of cities.
    Dim NumberOfCities As Integer
    'Variable that will be used to track the index of the loop to create worksheets.
    Dim SheetIndex As Integer

    NumberOfCities = Worksheets("Cities").UsedRange.Rows.Count

    For SheetIndex = 1 To NumberOfCities
        'Setting the cityname variable based on the index.
        CityName = Worksheets("Cities").Cells(SheetIndex, 1)
        'Adding a new worksheet called NewSheet to the workbook as last to ensure the alphabetical order.
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = CityName
    Next SheetIndex

End Sub
</code></pre>
<h2 id="heading-how-to-work-with-loops-in-vba">How to Work with Loops in VBA</h2>
<p>Let me explain how this all works. In the example above, I have declared two more variables, namely <code>CityName</code> and <code>SheetIndex</code>, which will hold the name of the city (which we'll use for the sheet title) and maintain the index of the loop.</p>
<p>The loop itself starts with the keyword <code>For</code>. Thereafter, we define the start of the index (one in this case) and loop through it until the number of cities has been reached. </p>
<p>For every iteration, the city has been stored in the variable <code>CityName</code>, which we then use to create a new worksheet. Run the function and you will see the worksheets being created with the title as defined in our Cities worksheet. It's magic, I know!</p>
<p>Now that the worksheets are there, we can add the single dates for the month. Earlier, we already defined the month we want to use in the Date worksheet. This can now help us create another loop so that all single days in the months are represented.</p>
<h2 id="heading-how-to-use-functions-in-vba">How to Use Functions in VBA</h2>
<p>But first we need to get the number of days of the month the user has entered in the tab Date. We can do this by using a function in VBA. Rather than the subroutines that we have used before, we can also use a function which returns something. </p>
<p>The function we are now using looks quite similar to the function you might use in Excel yourself when defining the number of days in a month (but you would use <code>Date</code> instead of <code>DateSerial</code>):</p>
<pre><code class="lang-vba">Function DaysInMonth(DateInput As Date)
    DaysInMonth = Day(DateSerial(Year(DateInput), Month(DateInput) + 1, 1) - 1)
End Function
</code></pre>
<p>You can enter this function either above or below the subroutine we defined before, as VBA is a compiled language rather than an interpreted one.</p>
<p><em>Note – although I will not paste the function again, it will be there for the remainder of this tutorial.</em></p>
<p>We can now use this function in our subroutine. This makes our lives a lot easier, as we can now use those superpowers without polluting our subroutine. </p>
<pre><code>Sub CreateTemplate()
    <span class="hljs-string">'Variable that will contain the cityname that is used to name a sheet.
    Dim CityName As String
    Dim MonthNum As Integer
    '</span>Variable that will contain the number <span class="hljs-keyword">of</span> cities.
    Dim NumberOfCities As Integer
    <span class="hljs-string">'Variable that will contain the date entered in the Date worksheet.
    Dim ReportDate As Date
    '</span>Variable that will be used to track the index <span class="hljs-keyword">of</span> the loop to create worksheets.
    Dim SheetIndex As Integer

    NumberOfCities = Worksheets(<span class="hljs-string">"Cities"</span>).UsedRange.Rows.Count

    For SheetIndex = <span class="hljs-number">1</span> To NumberOfCities
        <span class="hljs-string">'Setting the cityname variable based on the index.
        CityName = Worksheets("Cities").Cells(SheetIndex, 1)
        '</span>Adding a <span class="hljs-keyword">new</span> worksheet called NewSheet to the workbook <span class="hljs-keyword">as</span> last to ensure the alphabetical order.
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = CityName
    Next SheetIndex

    ReportDate = Worksheets(<span class="hljs-string">"Date"</span>).Cells(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
    Debug.Print DaysInMonth(ReportDate)

End Sub
</code></pre><p>For now, delete the worksheets with the city names if you had created them and run the macro (again) to make sure you got the correct number of days printed in the Immediate Window for the month you defined earlier in the Date worksheet.</p>
<p>We can then store the number of days as an integer in another variable (called <code>NumberOfDays</code>) for another loop. </p>
<pre><code>Sub CreateTemplate()
    <span class="hljs-string">'Variable that will contain the cityname that is used to name a sheet.
    Dim CityName As String
    '</span>Variable that will be used to track the index <span class="hljs-keyword">of</span> the loop to add the single dates <span class="hljs-keyword">for</span> the month.
    Dim DateIndex As Integer
    <span class="hljs-string">'Variable that will contain the number of cities.
    Dim NumberOfCities As Integer
    '</span>Variable that will contain the number <span class="hljs-keyword">of</span> days <span class="hljs-keyword">in</span> the chosen month
    Dim NumberOfDays As Integer
    <span class="hljs-string">'Variable that will contain the date entered in the Date worksheet.
    Dim ReportDate As Date
    '</span>Variable that will be used to track the index <span class="hljs-keyword">of</span> the loop to create worksheets.
    Dim SheetIndex As Integer

    NumberOfCities = Worksheets(<span class="hljs-string">"Cities"</span>).UsedRange.Rows.Count

    For SheetIndex = <span class="hljs-number">1</span> To NumberOfCities
        <span class="hljs-string">'Setting the cityname variable based on the index.
        CityName = Worksheets("Cities").Cells(SheetIndex, 1)
        '</span>Adding a <span class="hljs-keyword">new</span> worksheet called NewSheet to the workbook <span class="hljs-keyword">as</span> last to ensure the alphabetical order.
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = CityName
    Next SheetIndex

    ReportDate = Worksheets(<span class="hljs-string">"Date"</span>).Cells(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
    NumberOfDays = DaysInMonth(ReportDate)

    For SheetIndex = <span class="hljs-number">1</span> To NumberOfCities
        <span class="hljs-string">'Setting the cityname variable based on the index.
        CityName = Worksheets("Cities").Cells(SheetIndex, 1)

        For DateIndex = 1 To NumberOfDays
            Worksheets(CityName).Cells(DateIndex + 1, 1) = DateSerial(Year(ReportDate), Month(ReportDate), DateIndex)
        Next DateIndex
    Next SheetIndex

End Sub</span>
</code></pre><p>This will be a loop within a loop to spice it up a little! 🔥 </p>
<p>I will tell you what we are doing here. Again, we are looping through the cities. But instead of then creating another worksheet, we will now be doing something else with the <code>Cityname</code> variable.</p>
<p>In the loop inside the loop (you still get where I am now?) we are printing the date to the sheet, where, just like earlier in this tutorial, we used the <code>DateSerial</code> function.</p>
<p>Make sure to remove the sheets with a city name from your workbook, run the macro again, and you should see the worksheets including the dates for the month.</p>
<p>Note that the dates will be printed from the second row onwards, as I included +1 for my cell column in my code earlier. Why, you might ask yourself? Well, because I want to add certain titles on the first row instead, which we will add to the same loop right now.</p>
<p>Rather than defining the cells by using the Cells property followed by the row and column number as an integer, we can use <code>Range</code> followed by a cell's (or multiple cells') location to target its value and other properties.</p>
<pre><code class="lang-vba">    For SheetIndex = 1 To NumberOfCities
        'Setting the cityname variable based on the index.
        CityName = Worksheets("Cities").Cells(SheetIndex, 1)

        For DateIndex = 1 To NumberOfDays
            Worksheets(CityName).Cells(DateIndex + 1, 1) = DateSerial(Year(ReportDate), Month(ReportDate), DateIndex)
        Next DateIndex

        Worksheets(CityName).Range("B1") = "Minimum"
        Worksheets(CityName).Range("C1") = "Mean"
        Worksheets(CityName).Range("D1") = "Maximum"
    Next SheetIndex
</code></pre>
<p>In the example above I have added the headers for our table, which will now be printed to every single worksheet because of our loop. </p>
<h2 id="heading-how-to-use-arrays-in-vba">How to Use Arrays in VBA</h2>
<p>Every heard of DRY? Don't Repeat Yourself! Unfortunately, that is exactly what we are doing here. </p>
<p>An alternative could be to store the three headers in an array instead and loop over them to get to the same result. Is that really necessary for three items? Its debatable to be honest. But below you will find my code example as described:</p>
<pre><code>Sub CreateTemplate()
    <span class="hljs-string">'Variable that will contain the cityname that is used to name a sheet.
    Dim CityName As String
    '</span>Variable that will be used to track the index <span class="hljs-keyword">of</span> the loop to add the single dates <span class="hljs-keyword">for</span> the month.
    Dim DateIndex As Integer
    <span class="hljs-string">'Variable that will be used to track the index of the loop to insert the headers.
    Dim HeaderIndex As Integer
    '</span>Variant that will store the headers <span class="hljs-keyword">as</span> used <span class="hljs-keyword">in</span> every single worksheet.
    Dim Headers(<span class="hljs-number">2</span>) As Variant
    <span class="hljs-string">'Variable that will contain the number of cities.
    Dim NumberOfCities As Integer
    '</span>Variable that will contain the number <span class="hljs-keyword">of</span> days <span class="hljs-keyword">in</span> the chosen month
    Dim NumberOfDays As Integer
    <span class="hljs-string">'Variable that will contain the date entered in the Date worksheet.
    Dim ReportDate As Date
    '</span>Variable that will be used to track the index <span class="hljs-keyword">of</span> the loop to create worksheets.
    Dim SheetIndex As Integer

    Headers(<span class="hljs-number">0</span>) = <span class="hljs-string">"Minimum"</span>
    Headers(<span class="hljs-number">1</span>) = <span class="hljs-string">"Mean"</span>
    Headers(<span class="hljs-number">2</span>) = <span class="hljs-string">"Maximum"</span>

    NumberOfCities = Worksheets(<span class="hljs-string">"Cities"</span>).UsedRange.Rows.Count

    For SheetIndex = <span class="hljs-number">1</span> To NumberOfCities
        <span class="hljs-string">'Setting the cityname variable based on the index.
        CityName = Worksheets("Cities").Cells(SheetIndex, 1)
        '</span>Adding a <span class="hljs-keyword">new</span> worksheet called NewSheet to the workbook <span class="hljs-keyword">as</span> last to ensure the alphabetical order.
        Sheets.Add(After:=Sheets(Sheets.Count)).Name = CityName
    Next SheetIndex

    ReportDate = Worksheets(<span class="hljs-string">"Date"</span>).Cells(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
    NumberOfDays = DaysInMonth(ReportDate)

    For SheetIndex = <span class="hljs-number">1</span> To NumberOfCities
        <span class="hljs-string">'Setting the cityname variable based on the index.
        CityName = Worksheets("Cities").Cells(SheetIndex, 1)

        For DateIndex = 1 To NumberOfDays
            Worksheets(CityName).Cells(DateIndex + 1, 1) = DateSerial(Year(ReportDate), Month(ReportDate), DateIndex)
        Next DateIndex

        For HeaderIndex = 0 To UBound(Headers) - LBound(Headers)
            Worksheets(CityName).Cells(1, HeaderIndex + 2) = Headers(HeaderIndex)
        Next HeaderIndex

    Next SheetIndex

End Sub</span>
</code></pre><p>The variant is used as an array, which is declared where you would expect and the titles are inserted later per index direclty after the variable declaration. </p>
<p>Instead of providing the individual cell locations, I have used a loop which runs from zero to the number of items (minus one, as arrays in VBA start at zero too). The title is then printed to the sheet, just like in the previous situation. </p>
<p>You might need to add another header later on, in which case the latest solution is easier. But if you are a hundred percent sure you'll stick with three only, choose what is most convenient for you. It's best to know both ways after all. </p>
<p><em>It does not matter which of the two options you choose for the remainder of this tutorial, as long as you got the headers printed.</em></p>
<h2 id="heading-how-to-import-data-using-vba">How to Import Data Using VBA</h2>
<p>At this point we've created the actual template, so we can enter cities and a date in the workbook. Then the macro will do the rest for us. </p>
<p>I would like to go one step further in this tutorial and show you how to trigger an explorer window where you can choose a file and import the data from that file.</p>
<p>Make sure you have completed the steps above and have gotten the worksheets for all the cities. Let's start a new subroutine and define the following variables at the top:</p>
<pre><code>Sub ImportData()
    Dim FileLocation As <span class="hljs-built_in">String</span>
    Dim WorksheetTitle As <span class="hljs-built_in">String</span>

    WorksheetTitle = ActiveSheet.Name
End Sub
</code></pre><p>We need the first variable to store the location of the file where we are going to import the data on your device. We use the second one to store the title of the sheet that is currently selected by the user.</p>
<p>Add the following code to the macro, right below the line where we set the <code>WorksheetTitle</code> equal to the sheet name (but still before End Sub):</p>
<pre><code>FileLocation = Application.GetOpenFilename
If FileLocation = <span class="hljs-string">"False"</span> Then
    Beep
    Exit Sub
End If

Application.ScreenUpdating = False
<span class="hljs-built_in">Set</span> ImportWorkbook = Workbooks.Open(Filename:=FileLocation)

Debug.Print ImportWorkbook.Worksheets(<span class="hljs-number">1</span>).Range(<span class="hljs-string">"B1"</span>)

ImportWorkbook.Close
Application.ScreenUpdating = True
</code></pre><p>This might seem a little cryptic at first, but should not be to difficult to understand. The <code>Application.GetOpenFilename</code> function is what triggers a file explorer window and returns a location, which is then stored in the earlier defined variable.</p>
<p>If you decide not to select a file, meaning if the <code>FileLocation</code> = "False", you will hear the iconic beep sound (yes, Excel comes with awesome sounds too!😍) and the macro will end here.</p>
<p>If it's true, we'll continue with the macro, which first ends the screen updates of Excel. This helps make sure that everything will run smoothly. </p>
<p>For this macro you might not notice the difference without this line, but with more complex calculations you will. Believe me.</p>
<h2 id="heading-how-to-work-with-objects-in-vba">How to Work with Objects in VBA</h2>
<p>After that, the data included in the file that's located where the FileLocation variable is gets stored into the constant <code>ImportWorkbook</code>. </p>
<p>Note that we are using the <code>Set</code> keyword which is mainly used for objects, such as an import of a workbook. </p>
<p>To test whether we are able to extract the date from the file, we again use <code>Debug.Print</code> to print the city, which is located in cell B1 of the files available per the link mentioned in the beginning of this tutorial.</p>
<p>If you import the file <code>Data_Amsterdam</code>, you should see Amsterdam printed in your Immediate Window. After the file is closed, Excel will behave normally again. We can easily paste the (just printed) city name in the in our own template by replacing the <code>Debug.Print</code> with the following:</p>
<pre><code class="lang-vba">ThisWorkbook.Worksheets(WorksheetTitle).Range("A1") = ImportWorkbook.Worksheets(1).Range("B1")

'Equal to the following.
ThisWorkbook.Worksheets(WorksheetTitle).Cells(1, 1) = ImportWorkbook.Worksheets(1).Range(1, 2)
</code></pre>
<p>Note that we can now use our <code>ImportWorkbook</code> variable to get the data from the imported workbook. But we can also use <code>ThisWorkbook</code> (protected keyword name by VBA) to get to properties of our own template instead. </p>
<p>If we now run this macro and import <code>Data_Amsterdam</code>, the city should now be printed in the left-upper corner of your Amsterdam worksheet.</p>
<h2 id="heading-how-to-use-dictionaries-in-vba">How to Use Dictionaries in VBA</h2>
<p>As promised, now it's time to get the actual temperatures. You can use a loop and insert the numbers like demonstrated above, but I am feeling fancy today and would like to show you how we can do this using a dictionary.</p>
<p>Again, just like the array earlier in this tutorial, this approach might be a bit redundant for this situation. But if you need to work with larger amounts of data this will come in handy.</p>
<p>First thing we need to do is define several new variables here:</p>
<pre><code>Dim DataIndex As Integer
Dim DaysIndex As Integer
Dim FileLocation As <span class="hljs-built_in">String</span>
Dim Headers(<span class="hljs-number">2</span>) As Variant
Dim WorksheetTitle As <span class="hljs-built_in">String</span>
<span class="hljs-built_in">Set</span> TemperaturesDict = CreateObject(<span class="hljs-string">"Scripting.Dictionary"</span>)

Headers(<span class="hljs-number">0</span>) = <span class="hljs-string">"Maximum"</span>
Headers(<span class="hljs-number">1</span>) = <span class="hljs-string">"Minimum"</span>
Headers(<span class="hljs-number">2</span>) = <span class="hljs-string">"Mean"</span>
</code></pre><p>Both the indexes on top will track the index of the loops we will be using later. I copied the headers declaration and variables from our macro earlier. </p>
<p><em>Yes, we could have defined them as a global variable, but that is another topic for another day.</em> </p>
<p>Note that I have changed the order, as this is how they are displayed in the imported file.</p>
<p>A dictionary is also an object, which we will therefore declare using the <code>Set</code> keyword directly below our variables.</p>
<p>But before you can actually use a dictionary this way, make sure that you have Microsoft Scripting Runtime (as you can see in Figure 6 above) ticked, which you can find under Tools and then References in your editor.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/image-91.png" alt="Image" width="600" height="400" loading="lazy">
<em>Figure 06: Visual Basic References</em></p>
<p>Before, I showed you how to copy a value from a single cell from one workbook to a second one. Now, rather than copying single values, I want to store them all together in a dictionary before moving on and pasting them.</p>
<pre><code class="lang-vba">    For DaysIndex = 11 To ImportWorkbook.Worksheets(1).UsedRange.Rows.Count
        Set DataDict = CreateObject("Scripting.Dictionary")
        For DataIndex = 0 To 2
            DataDict.Add Headers(DataIndex), ImportWorkbook.Worksheets(1).Cells(DaysIndex, DataIndex + 2)
        Next DataIndex
        TemperaturesDict.Add DaysIndex, DataDict
    Next DaysIndex
</code></pre>
<p>This might be the most difficult part of the tutorial, which I will try to explain as clearly as possible. </p>
<p>We start with a loop like we've used many times before in this tutorial – so far so good. The loop starts at eleven and ends when the number of rows being used in the imported workbook is being reached.</p>
<p>Then, I am defining a new dictionary. Why? In most other languages it is possible to add new key value pairs using dot notation – but not in VBA. In order to so-called nest (add a dictionary in a dictionary), you will have to create a new (inner) dictionary and then add it to your other (outer) dictionary.</p>
<p>This dictionary in the loop will therefore first be populated with the different temperatures available, namely minimum, mean, and maximum. </p>
<p>To do this, I'll use the headers array as discussed above and I'll loop over these values. You add a key value pair by using the name of the dictionary followed by calling the <code>.Add</code> method, the key you want to use, a comma, and then its value:</p>
<pre><code class="lang-vba">DictName.Add Key, Value
</code></pre>
<p>This is what will be entered after the first iteration when you import the <code>Data_Amsterdam</code> file:</p>
<pre><code>Maximum: <span class="hljs-number">22.105547</span>
<span class="hljs-attr">Minimum</span>: <span class="hljs-number">14.385546</span>    
<span class="hljs-attr">Mean</span>: <span class="hljs-number">18.25388</span>
</code></pre><p>This dictionary then gets added to the 'main' dictionary called <code>TemperaturesDict</code> – meaning we'll now have something like this:</p>
<pre><code><span class="hljs-number">10</span>: 
    Maximum: <span class="hljs-number">22.105547</span>
    <span class="hljs-attr">Minimum</span>: <span class="hljs-number">14.385546</span>    
    <span class="hljs-attr">Mean</span>: <span class="hljs-number">18.25388</span>
</code></pre><p>We do the same for all the other days and temperature types, until the file is completely scraped and we are ready to insert this information into our template. But then what?</p>
<pre><code class="lang-vba">    Headers(0) = "Minimum"
    Headers(1) = "Mean"
    Headers(2) = "Maximum"

    For DaysIndex = 2 To ThisWorkbook.Worksheets(WorksheetTitle).UsedRange.Rows.Count
        If TemperaturesDict.Exists(DaysIndex - 1) Then
            For DataIndex = 0 To 2
                ThisWorkbook.Worksheets(WorksheetTitle).Cells(DaysIndex, DataIndex + 2) = TemperaturesDict(DaysIndex - 1)(Headers(DataIndex))
            Next DataIndex
        End If
    Next DaysIndex
</code></pre>
<p>As discussed above, the imported file has another order. But since we are using a dictionary, we can now easily reorder to headers array and have it displayed as we originally thought through in our template, as it will search for the key (#winning).</p>
<p>We are then using an old-fashioned loop to get over all the days we have in our template. The loop starts at two, as we defined our headers on the first row. Now starting at index one will override those, which we do not want. The loop ends after we have had all rows (that is to say, all days).</p>
<p>Since only a limited number of days are included in the imported file, we have to check whether the day equal to the index actually exists in our dictionary. </p>
<p>We do this with an if statement, which you might recognize from other coding languages. There is a minus one since our loop starts at two, though days of the month always start at one. The same counts for the minus one used later on in this block of code.</p>
<p>If the data actually exists in our array, we will insert it in our template. Then the row is defined by the index of the loop and the column comes from the <code>DataIndex</code>. </p>
<p>Eventually, we end up with the following code for our second macro:</p>
<pre><code>Sub ImportData()
    Dim DataIndex As Integer
    Dim DaysIndex As Integer
    Dim FileLocation As <span class="hljs-built_in">String</span>
    <span class="hljs-string">'Variant that will store the headers as used in every single worksheet.
    Dim Headers(2) As Variant
    Dim WorksheetTitle As String
    Set TemperaturesDict = CreateObject("Scripting.Dictionary")

    Headers(0) = "Maximum"
    Headers(1) = "Minimum"
    Headers(2) = "Mean"

    WorksheetTitle = ActiveSheet.Name

    FileLocation = Application.GetOpenFilename
    If FileLocation = "False" Then
        Beep
        Exit Sub
    End If

    Application.ScreenUpdating = False
    Set ImportWorkbook = Workbooks.Open(Filename:=FileLocation)

    For DaysIndex = 11 To ImportWorkbook.Worksheets(1).UsedRange.Rows.Count
        Set DataDict = CreateObject("Scripting.Dictionary")
        For DataIndex = 0 To 2
            DataDict.Add Headers(DataIndex), ImportWorkbook.Worksheets(1).Cells(DaysIndex, DataIndex + 2)
        Next DataIndex
        TemperaturesDict.Add DaysIndex, DataDict
    Next DaysIndex

    Headers(0) = "Minimum"
    Headers(1) = "Mean"
    Headers(2) = "Maximum"

    For DaysIndex = 2 To ThisWorkbook.Worksheets(WorksheetTitle).UsedRange.Rows.Count
        If TemperaturesDict.Exists(DaysIndex - 1) Then
            For DataIndex = 0 To 2
                ThisWorkbook.Worksheets(WorksheetTitle).Cells(DaysIndex, DataIndex + 2) = TemperaturesDict(DaysIndex - 1)(Headers(DataIndex))
            Next DataIndex
        End If
    Next DaysIndex

    ImportWorkbook.Close
    Application.ScreenUpdating = True

End Sub</span>
</code></pre><p>When you now run this code, you should see the the temperatures being imported from the data file to the template. </p>
<p>Note that we have also changed the order in which they originally come – now starting with minimum and ending with maximum. </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Congratulations! You have now made yourself a template which you can easily populate with data, all using macros.</p>
<p>Thank you for reading :) If you have any questions about this tutorial or other VBA implementation, please don't hesitate to send me a direct message on Twitter so I can help you out.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Excel VBA Tutorial – How to Write Code in a Spreadsheet Using Visual Basic ]]>
                </title>
                <description>
                    <![CDATA[ By Chloe Tucker Introduction This is a tutorial about writing code in Excel spreadsheets using Visual Basic for Applications (VBA). Excel is one of Microsoft’s most popular products. In 2016, the CEO of Microsoft said  "Think about a world without Ex... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/excel-vba-tutorial/</link>
                <guid isPermaLink="false">66d45e0033b83c4378a517d0</guid>
                
                    <category>
                        <![CDATA[ excel ]]>
                    </category>
                
                    <category>
                        <![CDATA[ VBA ]]>
                    </category>
                
                    <category>
                        <![CDATA[ visual basic ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 02 Jun 2020 13:00:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/06/excel-1771393_1920.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Chloe Tucker</p>
<h1 id="heading-introduction">Introduction</h1>
<p>This is a tutorial about writing code in Excel spreadsheets using Visual Basic for Applications (VBA).</p>
<p>Excel is one of Microsoft’s most popular products. In 2016, the CEO of Microsoft said  "Think about a world without Excel. That's just impossible for me.” Well, maybe the world can’t think without Excel.</p>
<ul>
<li>In 1996, there were over 30 million users of Microsoft Excel (<a target="_blank" href="https://news.microsoft.com/1996/05/20/more-than-30-million-users-make-microsoft-excel-the-worlds-most-popular-spreadsheet-program/">source</a>).</li>
<li>Today, there are an estimated 750 million users of Microsoft Excel. That’s a little more than the population of Europe and 25x more users than there were in 1996.</li>
</ul>
<p>We’re one big happy family!</p>
<p>In this tutorial, you’ll learn about VBA and how to write code in an Excel spreadsheet using Visual Basic.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>You don’t need any prior programming experience to understand this tutorial. However, you will need:</p>
<ul>
<li>Basic to intermediate familiarity with Microsoft Excel</li>
<li>If you want to follow along with the VBA examples in this article, you will need access to Microsoft Excel, preferably the latest version (2019) but Excel 2016 and Excel 2013 will work just fine.</li>
<li>A willingness to try new things</li>
</ul>
<h3 id="heading-learning-objectives">Learning Objectives</h3>
<p>Over the course of this article, you will learn:</p>
<ol>
<li>What VBA is</li>
<li>Why you would use VBA</li>
<li>How to get set up in Excel to write VBA</li>
<li>How to solve some real-world problems with VBA</li>
</ol>
<h3 id="heading-important-concepts">Important Concepts</h3>
<p>Here are some important concepts that you should be familiar with to fully understand this tutorial.</p>
<p><strong>Objects</strong>: Excel is object-oriented, which means everything is an object - the Excel window, the workbook, a sheet, a chart, a cell. VBA allows users to manipulate and perform actions with objects in Excel. </p>
<p>If you don’t have any experience with object-oriented programming and this is a brand new concept, take a second to let that sink in!</p>
<p><strong>Procedures</strong>: a procedure is a chunk of VBA code, written in the Visual Basic Editor, that accomplishes a task. Sometimes, this is also referred to as a macro (more on macros below). There are two types of procedures:</p>
<ul>
<li>Subroutines: a group of VBA statements that performs one or more actions</li>
<li>Functions: a group of VBA statements that performs one or more actions and returns one or more values</li>
</ul>
<p>Note: you can have functions operating inside of subroutines. You’ll see later.</p>
<p><strong>Macros</strong>: If you’ve spent any time learning more advanced Excel functionality, you’ve probably encountered the concept of a “macro.” Excel users can record macros, consisting of user commands/keystrokes/clicks, and play them back at lightning speed to accomplish repetitive tasks. Recorded macros generate VBA code, which you can then examine. It’s actually quite fun to record a simple macro and then look at the VBA code.</p>
<p>Please keep in mind that sometimes it may be easier and faster to record a macro rather than hand-code a VBA procedure. </p>
<p>For example, maybe you work in project management. Once a week, you have to turn a raw exported report from your project management system into a beautifully formatted, clean report for leadership. You need to format the names of the over-budget projects in bold red text. You could record the formatting changes as a macro and run that whenever you need to make the change.</p>
<h1 id="heading-what-is-vba">What is VBA?</h1>
<p>Visual Basic for Applications is a programming language developed by Microsoft. Each software program in the Microsoft Office suite is bundled with the VBA language at no extra cost. VBA allows Microsoft Office users to create small programs that operate within Microsoft Office software programs.</p>
<p>Think of VBA like a pizza oven within a restaurant. Excel is the restaurant. The kitchen comes with standard commercial appliances, like large refrigerators, stoves, and regular ole’ ovens - those are all of Excel’s standard features. </p>
<p>But what if you want to make wood-fired pizza? Can’t do that in a standard commercial baking oven. VBA is the pizza oven.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/1-Pizza.jpeg" alt="Pizza in a pizza oven" width="600" height="400" loading="lazy"></p>
<p>Yum.</p>
<h1 id="heading-why-use-vba-in-excel">Why use VBA in Excel?</h1>
<p>Because wood-fired pizza is the best!</p>
<p>But seriously.</p>
<p>A lot of people spend a <em>lot</em> of time in Excel as a part of their jobs. Time in Excel moves differently, too. Depending on the circumstances, 10 minutes in Excel can feel like eternity if you’re not able to do what you need, or 10 hours can go by very quickly if everything is going great. Which is when you should ask yourself, <strong>why on earth am I spending 10 hours in Excel?</strong></p>
<p>Sometimes, those days are inevitable. But if you’re spending 8-10 hours everyday in Excel doing repetitive tasks, repeating a lot of the same processes, trying to clean up after other users of the file, or even updating other files after changes are made to the Excel file, a VBA procedure just might be the solution for you.</p>
<p>You should consider using VBA if you need to:</p>
<ul>
<li>Automate repetitive tasks</li>
<li>Create easy ways for users to interact with your spreadsheets</li>
<li>Manipulate large amounts of data</li>
</ul>
<h1 id="heading-getting-set-up-to-write-vba-in-excel">Getting Set Up to Write VBA in Excel</h1>
<h2 id="heading-developer-tab">Developer Tab</h2>
<p>To write VBA, you’ll need to add the Developer tab to the ribbon, so you’ll see the ribbon like this.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/2-Developer-Tab.png" alt="VBA developer tab" width="600" height="400" loading="lazy"></p>
<p>To add the Developer tab to the ribbon:</p>
<ol>
<li>On the File tab, go to Options &gt; Customize Ribbon.</li>
<li>Under Customize the Ribbon and under Main Tabs, select the Developer check box.</li>
</ol>
<p>After you show the tab, the Developer tab stays visible, unless you clear the check box or have to reinstall Excel. <a target="_blank" href="https://support.office.com/en-us/article/show-the-developer-tab-e1192344-5e56-4d45-931b-e5fd9bea2d45">For more information, see Microsoft help documentation.</a></p>
<h2 id="heading-vba-editor">VBA Editor</h2>
<p>Navigate to the Developer Tab, and click the Visual Basic button. A new window will pop up - this is the Visual Basic Editor. For the purposes of this tutorial, you just need to be familiar with the Project Explorer pane and the Property Properties pane.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/VBA-Editor.png" alt="VBA editor" width="600" height="400" loading="lazy"></p>
<h1 id="heading-excel-vba-examples">Excel VBA Examples</h1>
<p>First, let’s create a file for us to play around in.</p>
<ol>
<li>Open a new Excel file</li>
<li>Save it as a macro-enabled workbook (. xlsm)</li>
<li>Select the Developer tab</li>
<li>Open the VBA Editor</li>
</ol>
<p>Let’s rock and roll with some easy examples to get you writing code in a spreadsheet using Visual Basic.</p>
<h2 id="heading-example-1-display-a-message-when-users-open-the-excel-workbook">Example #1: Display a Message when Users Open the Excel Workbook</h2>
<p>In the VBA Editor, select Insert -&gt; New Module</p>
<p>Write this code in the Module window (don’t paste!):</p>
<p>Sub Auto_Open()
  MsgBox ("Welcome to the XYZ Workbook.")
End Sub</p>
<p>Save, close the workbook, and reopen the workbook. This dialog should display.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/3-Welcome-to-XYZ-Notebook.png" alt="Welcome to XYZ notebook message example" width="600" height="400" loading="lazy"></p>
<p>Ta da!</p>
<h3 id="heading-how-is-it-doing-that">How is it doing that?</h3>
<p>Depending on your familiarity with programming, you may have some guesses. It’s not particularly complex, but there’s quite a lot going on:</p>
<ul>
<li>Sub (short for “Subroutine): remember from the beginning, “a group of VBA statements that performs one or more actions.”</li>
<li>Auto_Open: this is the specific subroutine. It automatically runs your code when the Excel file opens - this is the event that triggers the procedure. Auto_Open will only run when the workbook is opened manually; it will not run if the workbook is opened via code from another workbook (Workbook_Open will do that, <a target="_blank" href="https://www.pcreview.co.uk/threads/auto_open-vs-workbook_open.953960/">learn more about the difference between the two</a>).</li>
<li>By default, a subroutine’s access is public. This means any other module can use this subroutine. All examples in this tutorial will be public subroutines. If needed, you can declare subroutines as private. This may be needed in some situations. <a target="_blank" href="https://www.thespreadsheetguru.com/blog/2014/3/5/explaining-private-vs-public-declarations">Learn more about subroutine access modifiers.</a></li>
<li>msgBox: this is a function - a group of VBA statements that performs one or more actions and returns a value. The returned value is the message “Welcome to the XYZ Workbook.”</li>
</ul>
<p>In short, this is a simple subroutine that contains a function.</p>
<h3 id="heading-when-could-i-use-this">When could I use this?</h3>
<p>Maybe you have a very important file that is accessed infrequently (say, once a quarter), but automatically updated daily by another VBA procedure. When it is accessed, it’s by many people in multiple departments, all across the company.</p>
<ul>
<li>Problem: Most of the time when users access the file, they are confused about the purpose of this file (why it exists), how it is updated so often, who maintains it, and how they should interact with it. New hires always have tons of questions, and you have to field these questions over and over and over again.</li>
<li>Solution: create a user message that contains a concise answer to each of these frequently answered questions.</li>
</ul>
<h3 id="heading-real-world-examples">Real World Examples</h3>
<ul>
<li>Use the MsgBox function to display a message when there is any event: user closes an Excel workbook, user prints, a new sheet is added to the workbook, etc.</li>
<li>Use the MsgBox function to display a message when a user needs to fulfill a condition before closing an Excel workbook</li>
<li>Use the InputBox function to get information from the user</li>
</ul>
<h2 id="heading-example-2-allow-user-to-execute-another-procedure">Example #2: Allow User to Execute another Procedure</h2>
<p>In the VBA Editor, select Insert -&gt; New Module</p>
<p>Write this code in the Module window (don’t paste!):                </p>
<p>Sub UserReportQuery()
Dim UserInput As Long
Dim Answer As Integer
UserInput = vbYesNo
Answer = MsgBox("Process the XYZ Report?", UserInput)
If Answer = vbYes Then ProcessReport
End Sub</p>
<p>Sub ProcessReport()
MsgBox ("Thanks for processing the XYZ Report.")
End Sub</p>
<p>Save and navigate back to the Developer tab of Excel and select the “Button” option. Click on a cell and assign the UserReportQuery macro to the button.</p>
<p>Now click the button. This message should display:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/4-Process-the-Report.png" alt="Process the XYZ report message example" width="600" height="400" loading="lazy"></p>
<p>Click “yes” or hit Enter.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/5-Thanks-for-Processing-the-Report.png" alt="Thanks for processing the XYZ report message example" width="600" height="400" loading="lazy"></p>
<p>Once again, tada!</p>
<p>Please note that the secondary subroutine, ProcessReport, could be <em>anything</em>. I’ll demonstrate more possibilities in example #3. But first...</p>
<h3 id="heading-how-is-it-doing-that-1">How is it doing that?</h3>
<p>This example builds on the previous example and has quite a few new elements. Let’s go over the new stuff:</p>
<ul>
<li>Dim UserInput As Long: Dim is short for “dimension” and allows you to declare variable names. In this case, UserInput is the variable name and Long is the data type. In plain English, this line means “Here’s a variable called “UserInput”, and it’s a Long variable type.”</li>
<li>Dim Answer As Integer: declares another variable called “Answer,” with a data type of Integer. <a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/data-types/">Learn more about data types here.</a></li>
<li>UserInput = vbYesNo: assigns a value to the variable. In this case, vbYesNo, which displays Yes and No buttons. There are <em>many</em> button types, <a target="_blank" href="https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/msgbox-function">learn more here</a>.</li>
<li>Answer = MsgBox(“Process the XYZ Report?”, UserInput): assigns the value of the variable Answer to be a MsgBox function and the UserInput variable. Yes, a variable within a variable.</li>
<li>If Answer = vbYes Then ProcessReport: this is an “If statement,” a conditional statement, which allows us to say if x is true, then do y. In this case, if the user has selected “Yes,” then execute the ProcessReport subroutine.</li>
</ul>
<h3 id="heading-when-could-i-use-this-1">When could I use this?</h3>
<p>This could be used in many, many ways. The value and versatility of this functionality is more so defined by what the secondary subroutine does.</p>
<p>For example, maybe you have a file that is used to generate 3 different weekly reports. These reports are formatted in dramatically different ways.</p>
<ul>
<li>Problem: Each time one of these reports needs to be generated, a user opens the file and changes formatting and charts; so on and so forth. This file is being edited extensively at least 3 times per week, and it takes at least 30 minutes each time it’s edited.</li>
<li>Solution: create 1 button per report type, which automatically reformats the necessary components of the reports and generates the necessary charts.</li>
</ul>
<h3 id="heading-real-world-examples-1">Real World Examples</h3>
<ul>
<li>Create a dialog box for user to automatically populate certain information across multiple sheets</li>
<li>Use the InputBox function to get information from the user, which is then populated across multiple sheets</li>
</ul>
<h2 id="heading-example-3-add-numbers-to-a-range-with-a-for-next-loop">Example #3: Add Numbers to a Range with a For-Next Loop</h2>
<p>For loops are very useful if you need to perform repetitive tasks on a specific range of values - arrays or cell ranges. In plain English, a loop says “for each x, do y.”</p>
<p>In the VBA Editor, select Insert -&gt; New Module</p>
<p>Write this code in the Module window (don’t paste!):</p>
<p>Sub LoopExample()
Dim X As Integer
For X = 1 To 100
    Range("A" &amp; X).Value = X
Next X
End Sub</p>
<p>Save and navigate back to the Developer tab of Excel and select the Macros button. Run the LoopExample macro.</p>
<p>This should happen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/Screen-Shot-2020-06-01-at-2.53.02-PM.png" alt="For-Next loop results" width="600" height="400" loading="lazy"></p>
<p>Etc, until the 100th row.</p>
<h3 id="heading-how-is-it-doing-that-2">How is it doing that?</h3>
<ul>
<li>Dim X As Integer: declares the variable X as a data type of Integer.</li>
<li>For X = 1 To 100: this is the start of the For loop. Simply put, it tells the loop to keep repeating until X = 100. X is the <em>counter</em>. The loop will keep executing until X = 100, execute one last time, and then stop.</li>
<li>Range("A" &amp; X).Value = X: this declares the range of the loop and what to put in that range. Since X = 1 initially, the first cell will be A1, at which point the loop will put X into that cell.</li>
<li>Next X: this tells the loop to run again</li>
</ul>
<h3 id="heading-when-could-i-use-this-2">When could I use this?</h3>
<p>The For-Next loop is one of the most powerful functionalities of VBA; there are numerous potential use cases. This is a more complex example that would require multiple layers of logic, but it communicates the world of possibilities in For-Next loops.</p>
<p>Maybe you have a list of all products sold at your bakery in Column A, the type of product in Column B (cakes, donuts, or muffins), the cost of ingredients in Column C, and the market average cost of each product type in another sheet. </p>
<p>You need to figure out what should be the retail price of each product. You’re thinking it should be the cost of ingredients plus 20%, but also 1.2% under market average if possible. A For-Next loop would allow you to do this type of calculation.</p>
<h3 id="heading-real-world-examples-2">Real World Examples</h3>
<ul>
<li>Use a loop with a nested if statement to add specific values to a separate array only if they meet certain conditions</li>
<li>Perform mathematical calculations on each value in a range, e.g. calculate additional charges and add them to the value</li>
<li>Loop through each character in a string and extract all numbers</li>
<li>Randomly select a number of values from an array</li>
</ul>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Now that we’ve talked about pizza and muffins and oh-yeah, how to write VBA code in Excel spreadsheets, let’s do a learning check. See if you can answer these questions.</p>
<ul>
<li>What is VBA?</li>
<li>How do I get set up to start using VBA in Excel?</li>
<li>Why and when would you use VBA?</li>
<li>What are some problems I could solve with VBA?</li>
</ul>
<p>If you have a fair idea of how to you could answer these questions, then this was successful.</p>
<p>Whether you’re an occasional user or a power user, I hope this tutorial provided useful information about what can be accomplished with just a bit of code in your Excel spreadsheets.</p>
<p>Happy coding!</p>
<h2 id="heading-learning-resources">Learning Resources</h2>
<ul>
<li>Excel VBA Programming for Dummies, John Walkenbach</li>
<li><a target="_blank" href="https://docs.microsoft.com/en-us/office/vba/library-reference/concepts/getting-started-with-vba-in-office">Get Started with VBA, Microsoft Documentation</a></li>
<li><a target="_blank" href="https://www.lynda.com/Excel-tutorials/Learning-VBA-Excel/802840-2.html?srchtrk=index%3a5%0alinktypeid%3a2%0aq%3avba%0apage%3a1%0as%3arelevance%0asa%3atrue%0aproducttypeid%3a2">Learning VBA in Excel, Lynda</a></li>
</ul>
<h2 id="heading-a-bit-about-me">A bit about me</h2>
<p>I'm Chloe Tucker, an artist and developer in Portland, Oregon. As a former educator, I'm continuously searching for the intersection of learning and teaching, or technology and art. Reach out to me on Twitter <a target="_blank" href="https://twitter.com/_chloetucker">@_chloetucker</a> and check out my website at <a target="_blank" href="https://chloe.dev/">chloe.dev</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
