Excel VBA (Visual Basic for Applications) is a powerful tool for automating tasks and processes in Microsoft Excel. It allows you to create complex scripts to manipulate data, perform calculations, and make decisions. Conditional logic is a fundamental part of programming, and in this comprehensive guide, we’ll delve into If-Then-Else statements in Excel VBA.
The Power of Conditional Logic:
Conditional logic in Excel VBA enables you to make your code smarter by allowing it to respond to specific conditions. If-Then-Else statements provide a way to execute different code blocks based on whether a particular condition is met. These statements are essential for creating dynamic, responsive, and intelligent Excel applications.
The If-Then Statement:
The If-Then statement is the building block of conditional logic. It allows you to execute code lines when a specified condition is true. Here’s a more detailed look at how to use If-Then in Excel VBA:
We declare two variables, score and result, and retrieve the value in cell A1.
The If statement checks if the score is greater than or equal to 60.
If the condition is true, it assigns “Pass” to the result variable.
The result is then displayed in cell B1.
This basic If-Then structure sets the stage for more advanced decision-making processes.
The If-Then-Else Statement:
The If-Then-Else statement extends conditional logic to provide two different outcomes based on whether a condition is true or false. Here’s how it works:
We use the If-Then-Else structure to determine whether the score is above or below 60.
If the score is greater than or equal to 60, the result is set to “Pass.”
If not, the result is assigned “Fail.”
This more advanced logic allows you to create applications that respond dynamically to various scenarios.
Conclusion:
Conditional logic is an indispensable part of Excel VBA programming, enabling you to build intelligent, automated solutions. If-Then-Else statements provide the tools you need to create applications that respond to specific conditions, making your work in Excel more efficient and dynamic. With this knowledge, you can take your Excel skills to the next level.
Unlocking the power of formatting in Excel VBA is essential for creating professional and visually appealing spreadsheets. This guide will walk you through using fonts and colors to make your data stand out and convey information more effectively.
Mastering Font Properties:
In Excel VBA, the Font property of the Range object is your gateway to a range of formatting options. The Font object offers properties like Color and Bold, allowing you to take control of your text.
Color Property:
To change the text color in your Excel range, employ the Font property, and then the Color property of the Font object:
Code:
Range("A1").Font.Color=RGB(255,0,0) ' Set the text color to pure Red
Excel VBA provides built-in constants like vbRed for common colors:
Code:
Range("A1").Font.Color=vbRed' Set the text color to Red
Bold Property:
You can easily make text bold with Excel VBA:
Code:
Range("A1").Font.Bold=True' Make the text bold
To unbold text, simply use the False keyword.
Changing Background Colors:
Manipulating background colors in VBA is straightforward. Use the Interior property to return an Interior object. Then, adjust the background color with the ColorIndex property:
Set the background color of cell A1 to light blue:
Code:
Range("A1").Interior.ColorIndex=37
Clear the background color (set it to ‘No Fill’):
Code:
Range("A1").Interior.ColorIndex=0
If you need to determine the ColorIndex number of a color, Excel VBA can provide the answer:
Code:
MsgBoxSelection.Interior.ColorIndex
Utilize the Color property and the RGB function for more extensive color customization. RGB stands for Red, Green, and Blue, offering a full spectrum of colors. For example, RGB(255, 0, 0) results in pure Red.
The Range object is a powerhouse in Excel VBA, and understanding its properties and methods is essential for effective VBA programming. In this comprehensive guide, we’ll delve into the versatility of Range objects and how they can be harnessed to perform a variety of tasks in Excel.
Range Object Basics
The Range object is the representation of a cell or cells on your worksheet and is the cornerstone of Excel VBA. Let’s explore its properties and methods, which are crucial for manipulating data.
Examples of Range Usage:
Setting values to a specific cell:
Code:
Range("B3").Value=2
Setting values to a range of cells:
Code:
Range("A1:A4").Value=5
Setting values to non-contiguous ranges:
Code:
Range("A1:A2,B3:C4").Value=10
Working with Cells
While the Range object is powerful, you can also achieve specific cell interactions using the Cells property.
Set the value of a specific cell:
Code:
Cells(3,2).Value=2
Copy data from one range to another:
Code:
Range("C3:C4").Value=Range("A1:A2").Value
Declaring a Range Object
In Excel VBA, declaring a Range object is a common practice for efficient coding.
The CurrentRegion property defines a range bounded by any combination of blank rows and columns.
Find the CurrentRegion of cell A1:
Code:
Range("A1").CurrentRegion.Select
Find the CurrentRegion of cell B3:
Code:
Range("B3").CurrentRegion.Select
Dynamic Range and Coloring Max Value
This code snippet demonstrates coloring the maximum value in a dynamic range.
Code:
' Insert your dynamic rangeDimrngAsRangeSetrng=Range("A1:A10")' Find the maximum value in the rangemaximum=WorksheetFunction.Max(rng)' Color the maximum valueForEachcellInrngIfcell.Value=maximumThencell.Interior.ColorIndex=22Nextcell
Resizing Ranges with Resize
The Resize property allows you to make a range larger or smaller by specifying the number of rows and columns.
Code:
Range("A1:C4").Resize(3,2).Select
Code:
Range("A1:C4").Resize(,1).Select
Union and Intersect Methods
The Union and Intersect methods enable you to work with multiple ranges at once.
Union of two ranges:
Code:
Union(Range("B2:C7"),Range("C6:F8")).Select
Intersect of two ranges:
Code:
Intersect(Range("B2:C7"),Range("C6:F8")).Select
Testing a Selection
You can test a selection in Excel VBA using Count, IsNumeric, IsEmpty, and Intersect.
Working with the Areas Collection:
Counting Areas:To determine the number of areas within a given range, use the Areas.Count property.
Result: This code will display the count of areas within the specified range.
Accessing Specific Areas:You can access specific areas within a range by using index values. The following code counts the number of cells in the first area.
Code:
MsgBoxrangeToUse.Areas(1).Count
Result: This code displays the count of cells in the first area of the range.
Looping Through Areas:To process each area in a range and count the cells in each area, you can use a loop. The following code does just that:
Result: This code will display the count of cells in each area of the range.
Comparing Ranges:
Scenario:You have randomly selected ranges, and you want to highlight cells that contain unique values. This code will help identify values that only appear once across all selected ranges.
Code:
DimrangeToUseAsRange,singleAreaAsRange,cell1AsRange,cell2AsRange,iAsInteger,jAsIntegerSetrangeToUse=SelectionCells.Interior.ColorIndex=0Cells.Borders.LineStyle=xlNoneIfSelection.Areas.Count<=1ThenMsgBox"Please select more than one area."ElserangeToUse.Interior.ColorIndex=38ForEachsingleAreaInrangeToUse.AreassingleArea.BorderAround ColorIndex:=1, Weight:=xlThinNextsingleAreaFori=1TorangeToUse.Areas.CountForj=i+1TorangeToUse.Areas.CountForEachcell1InrangeToUse.Areas(i)ForEachcell2InrangeToUse.Areas(j)Ifcell1.Value=cell2.ValueThencell1.Interior.ColorIndex=0cell2.Interior.ColorIndex=0EndIfNextcell2Nextcell1NextjNextiEndIf
Result: This code will highlight unique values in the selected ranges while removing the highlighting for non-unique values.
Mastering Offset Property:
The Offset property is a powerful tool in Excel VBA, enabling you to navigate to specific cells relative to a starting point. Let’s explore its applications:
Result: These code lines select the range that is 3 rows below and 2 columns to the right of Range(“A1:A2”). Remember that Offset always takes the top left cell of a range as the starting point.
From Active Cell to Last Entry:
The End property is a valuable asset in Excel VBA, especially when you need to find the last entry in a column. Let’s see how it works:
Selecting the Last Entry in a Column:
Code:
Range("A5").End(xlDown).Select
Note: You can use various starting points such as Range(“A1”) or Range(“A2”). This code line is equivalent to pressing the END+DOWN ARROW.
Result: The last entry in the column is selected.
Selecting a Range to the Last Entry:
Code:
Range(Range("A5"),Range("A5").End(xlDown)).Select
Result: This code line selects the range from cell A5 to the last entry in the column.
Selecting from the Active Cell to the Last Entry:
Code:
ange(ActiveCell,ActiveCell.End(xlDown)).Select
Result: When you select any cell, this code line chooses the range from the active cell down to the last entry in the column.
You’re not limited to moving down; you can use constants like xlUp, xlToRight, and xlToLeft to navigate in other directions, allowing for versatile and precise selections.
Final Thoughts
Mastering Range objects is crucial for proficient Excel VBA programming. These objects empower you to manipulate data with precision and flexibility, making your Excel tasks more efficient and automated. These skills are invaluable for handling complex data analysis tasks with ease.
Welcome to a comprehensive guide on mastering VBA (Visual Basic for Applications) variables. In this combined edition, we’ll explore the intricacies of variables in VBA, covering essential concepts from our beginner’s guide.
Declaring Variables Part 1
In this section, we delved into the world of declaring, initializing, and displaying variables in Excel VBA. Here’s a glimpse of what you learned:
1. Integer Variables
Integer variables are designed to store whole numbers. You declared an Integer variable, initialized it, and displayed its value in Cell A1.
Code:
DimxAsIntegerx=6Range("A1").Value=x
The first code line declares a variable with name x of type Integer. We initialize x with value 6. So we write the value of x to cell A1.
2. String Variables
String variables, your gateway to storing text, were explored. You declared a String variable, initialized it, and wrote the text to Cell A1.
Code:
DimbookAsStringbook="bible"Range("A1").Value=book
The first code line declares a variable with name book of type String. We initialize book with the text bible. Always use apostrophes to initialize String variables. We write the text of the variable book to cell A1.
3. Double Variables
Double variables, offering higher precision, were introduced. We emphasized the importance of choosing the correct variable type for your needs.
Code:
DimxAsDoublex=5.5MsgBox"value is "&x
Long variables have even larger capacity. Always use variables of the right type. As a result, errors are easier to find and your code will run faster.
4. Boolean Variables
Boolean variables, capable of holding True or False values, were explained. You used a Boolean variable to trigger a MsgBox based on the value held.
Code:
Dimcontinue As Booleancontinue=TrueIfcontinue=TrueThenMsgBox"Boolean variables are cool"
The first code line declares a variable with name continue of type Boolean. We initialize continue with the value True. We use the Boolean variable to only display a MsgBox if the variable holds the value True.
Declaring Variables Part 2 – Option Explicit
In this section, we discussed the vital importance of Option Explicit in your VBA code. Here’s a summary of what you discovered:
Option Explicit
We strongly recommended using Option Explicit at the beginning of your Excel VBA code. It enforces variable declaration and helps identify issues related to variables. We demonstrated how missing or incorrectly declared variables can lead to errors.
Absolutely, here are improved steps for instructing Excel VBA to automatically add Option Explicit:
Open the Visual Basic Editor by going to the “Developer” tab and clicking “Visual Basic” or by using the shortcut Alt + F11.
In the Visual Basic Editor, go to the “Tools” menu.
Select “Options” from the Tools menu.
In the Options dialog box, under the “Editor” tab, ensure that “Require Variable Declaration” is checked.
Click “OK” to save your preferences.
By following these steps, you’ll have Option Explicit automatically added to your Excel VBA code, helping you avoid common programming errors.
Automating Option Explicit
We also showed you how to instruct Excel VBA to automatically add Option Explicit to your code, saving you from unnecessary debugging and errors.
By combining the knowledge from these sections, you’re well on your way to becoming a proficient VBA programmer. Stay tuned for more chapters, where we’ll explore advanced topics and practical applications of VBA in Excel.
Welcome to Chapter 1 of our journey into the world of VBA (Visual Basic for Applications) Macros, the programming language that empowers Excel and various Office programs. In this introductory chapter, we’ll explore the basics and key abbreviations you need to kickstart your VBA learning adventure.
Chapter 1: Navigating the VBA Universe
VBA stands for Visual Basic for Applications, and it serves as the bridge between you and the power of automation. Let’s delve into the essential points you’ll encounter on your VBA/Macros journey:
1. Creating Macros with VBA
VBA is your gateway to automating tasks through the creation of macros. With VBA, you can script out sequences of actions to make Excel work for you, streamlining your workflow.
2. The MsgBox Function
The MsgBox, short for message box, is your tool for communicating with users. You can use it to provide information, warnings, or gather input from users within your VBA applications.
3. Understanding Workbook and Worksheet Objects
In the VBA world, workbooks and worksheets are objects you’ll frequently interact with. Learning the ins and outs of these objects is fundamental for VBA coding.
4. Exploring the Range Object
The Range object is your window into manipulating cells and data on your Excel worksheet. Understanding how to work with this object is essential for any VBA developer.
5. Mastering Variables
In this chapter, you’ll get to grips with variables. Learn how to declare, initialize, and display variables in VBA, a crucial skill for data manipulation.
6. The Power of If-Then Statements
Conditional logic is a fundamental building block in programming. Discover how to use the If-Then statement to execute specific code lines when specific conditions are met.
7. Unleashing the Potential of Loops
Loops are a programming powerhouse, allowing you to iterate through sets of data or perform repetitive tasks with minimal code. You’ll learn how to harness loops in VBA.
8. Handling Macro Errors
Every programmer faces errors. This chapter equips you with the skills to tackle and manage errors that may occur in your VBA code.
9. String Manipulation
Manipulating strings is essential in VBA. You’ll discover critical string functions to enhance your text-processing capabilities.
10. Working with Dates and Times
Date and time operations are vital in many applications. You’ll become proficient in managing dates and times within your VBA programs.
11. Understanding Events
Events are the triggers that initiate VBA code execution. Learn how user actions can activate your VBA macros.
12. Grasping Arrays
Arrays allow you to group variables. This chapter shows you how to work with arrays, accessing specific elements by using the array name and index number.
13. Functions and Subs in VBA
Explore the difference between functions and subs in VBA. Functions can return values, while subs perform actions without returning values.
14. The Application Object
The Application object is the master of all objects in Excel. It grants access to a multitude of Excel-related options. Get ready to unlock its potential.
15. Creating ActiveX Controls
Learn how to create ActiveX controls, including command buttons, text boxes, and list boxes, to enhance your VBA applications.
16. Building a VBA Userform
Discover the art of creating a VBA Userform, a valuable tool for enhancing the user experience in your VBA applications.
Our journey into the world of VBA Macros has just begun. Stay tuned for an exciting and informative series that will guide you through the ins and outs of VBA programming in Excel and beyond.
Creating Your First Macro
we ventured into the practical aspects of VBA Macros. Here are the essential learnings:
Creating Macros with VBA
VBA empowers you to automate tasks in Excel. Chapter 2 focused on creating a simple macro that executes after clicking a command button.
Turning on the Developer Tab
We initiated our practical journey by enabling the Developer tab, a critical step in working with VBA.
Adding a Command Button
You learned how to insert a command button, a pivotal tool for triggering VBA macros.
Assigning a Macro
The chapter guided you through the process of assigning a macro to a command button, setting your VBA macro in motion.
Creating Your First Macro
With practical steps, you created your first macro in Excel, typing “Hello” into Cell A1.
Our comprehensive guide to VBA Macros has just begun. Stay tuned for upcoming chapters where we’ll explore range selection, formatting, copy/paste techniques, and much more in Excel.
Have you ever experienced the sensation of your mobile phone vibrating or ringing, only to find out that there was no incoming call or message? This intriguing phenomenon is known as Phantom Vibration Syndrome, sometimes humorously called “ringxiety” or “fauxcellarm.” While it’s not technically a syndrome, it’s an intriguing tactile hallucination where the brain perceives a sensation that doesn’t exist.
Phantom vibrations can strike at unexpected times – during a relaxing shower, while engrossed in a TV show, or while using a noisy device. The curious thing is that we’re exceptionally sensitive to auditory tones between 1,000 and 6,000 hertz, a range where basic mobile phone ringers often operate. These phantom sensations often develop after using a cell phone set to vibrate for alerts. In fact, a study by researcher Michelle Drouin revealed that nearly 90% of undergraduates at her college had experienced these phantom vibrations.
Interestingly, this isn’t a new concept. In Scott Adams’ Dilbert comic strip, he humorously referred to it as “phantom-pager syndrome” as far back as 1996. The term “phantom vibration syndrome” made its earliest appearance in a 2003 article titled “Phantom Vibration Syndrome” in the New Pittsburgh Courier. In the article, the author pondered the implications of this growing phenomenon in our “always on” society.
The first formal study of this phenomenon occurred in 2007, and the term “ringxiety” was coined to describe it. Remarkably, in 2012, “phantom vibration syndrome” was recognized as the Word of the Year by the Australian Macquarie Dictionary.
The cause of phantom vibrations remains a mystery. While researchers suspect it’s linked to our increasing attachment to our mobile phones, the exact mechanisms are not well understood. Vibrations usually begin occurring after using a phone for a few months to a year. It’s theorized that when we anticipate a call, the brain may misinterpret other sensory inputs, such as muscle contractions, pressure from clothing, or even music, as a phone vibration or ringtone.
Most studies reveal that a majority of cell phone users have experienced occasional phantom vibrations or ringing, with reported rates ranging from 27.4% to a staggering 89%. For many, these sensations occur approximately once every two weeks, though a minority experiences them daily. Fortunately, most people aren’t overly troubled by these phantom sensations.
As for treatment, there’s little research available. Some individuals find relief by changing the phone’s position, turning off vibrate mode, or switching to a different device. The mystery of these phantom phone calls and vibrations continues to perplex, making it a fascinating yet unexplained quirk of our digital age.
Formulas and functions are essential tools in Excel, empowering users to perform calculations ranging from simple to complex. While both serve mathematical purposes, they differ significantly in their nature and application.
Key Distinctions Between Formulas and Functions
Customization: A formula in Excel is a user-defined statement capable of incorporating a wide range of operations, tailored to specific calculation needs. In contrast, a function is a predefined operation provided by Excel, limiting customization to the available parameters.
Scope: Formulas can operate within a single cell or across a range of cells, facilitating intricate calculations. Functions, on the other hand, are designed for quick and common tasks like finding minimum or maximum values, averages, and more.
Modification: Functions can be adjusted as needed by developers, altering their parameters to suit different scenarios. Formulas, however, lack this flexibility and are used only when explicitly needed.
Interchangeability: Functions can be used within formulas, but formulas cannot be used as functions. This distinction underscores the versatility of functions for complex calculations.
Usability: While formulas can handle simple manual calculations, functions excel in tackling complex operations efficiently. Functions come with predefined syntax, making them more structured and accessible for users.
Parameters: Functions are equipped with predefined parameters that dictate their behavior. Formulas lack these built-in parameters and require manual specification.
Examples of Formulas
To create a formula in Excel, users initiate it with an equal sign. Here are some examples:
=4+13=A3+C19=B77+B8-(4*2)+
Examples of Functions
Functions are invoked by typing an equal sign followed by a predefined set of letters or by using the function wizard (Fx button in the formula bar). Some examples include:
=SUM(A2:A27)=AVERAGE(F2:F8)=NPV(0.10,A5:G5)
Combining Formulas and Functions
Users can harness the combined power of formulas and functions to perform intricate analyses. Examples of such combinations include:
From a communication and comprehension perspective, there isn’t a substantial difference between formulas and functions. However, it’s important to recognize that functions are predefined, code-like operations, while formulas are user-crafted statements. Both are indispensable tools for data analysis and calculations in Excel.
Oxytocin, often referred to as the “love hormone,” has long been associated with the warm, fuzzy feelings we experience in moments of affection. However, recent scientific discoveries have revealed that this remarkable molecule serves a broader role, extending far beyond the realms of love. It turns out that oxytocin also plays a pivotal role in shaping our sociability, enhancing our ability to engage with the intricate social fabric around us.
Researchers are now harnessing this newfound knowledge in their laboratories, unearthing oxytocin’s immense potential in treating various social disorders, such as drug addiction and alcoholism. In a quest to uncover the secrets of oxytocin, Dr. Graham Phillips delves into the latest scientific developments.
Dr. Graham Phillips, a dedicated investigator in the field, sheds light on the idea that the oxytocin system undergoes crucial development during childhood. It now appears that the proper maturation of this system during those formative years is essential for our adult well-being. Conversely, a lack of proper development may render individuals more susceptible to conditions like alcoholism and drug addiction later in life.
The potential of oxytocin in reshaping the landscape of social disorders represents a promising avenue of research, offering hope to those in need. As our understanding of oxytocin’s influence on social behaviors and disorders continues to grow, we may find innovative solutions to address these challenges.
Laughter is a fascinating human response, often triggered by the delightful act of tickling. Most of us have a ticklish spot somewhere on our bodies, and it’s usually a fun game to find it. Whether it’s just above the knee, the back of the neck, or those sides that make us burst into fits of laughter, being tickled by another person is a universal experience. But have you ever wondered why we laugh when tickled? Recent scientific findings reveal that this seemingly whimsical reaction has roots in our primal instincts, serving as a defense mechanism against little creepy crawlers like spiders and bugs.
When we’re tickled, even by the gentle touch of insects, our bodies react with a shiver, signaling that something might be crawling on us. This ticklish sensation can trigger a panic response. It’s this unexpected and uneasy feeling that leads to the intense laughter we experience when someone tickles us, catching us off guard.
Surprisingly, even if we’re aware that a tickling is imminent, the fear and unease of another person’s touch can still provoke laughter. Some individuals are so ticklish that they can’t help but burst into laughter even before being touched.
Now, the question arises: Why can’t we tickle ourselves? The full explanation remains a bit of a mystery, but research has shown that our brains are finely tuned to anticipate the sensations generated by our own movements. Just as you don’t consciously focus on the sensations of your vocal cords when you speak, your brain dismisses many self-generated sensations. When we attempt to tickle ourselves by, for instance, grabbing our own sides, our brain expects this self-contact and prepares for it. This anticipation eliminates the element of surprise and unease, causing our body to respond differently compared to when someone else tickles us.
Brain scientists at the University College London have identified the cerebellum as the part of the brain responsible for preventing self-tickling. Located at the base of the brain, the cerebellum constantly monitors our movements and can distinguish between expected and unexpected sensations. Expected sensations, like the pressure of your fingers on a keyboard, are filtered out, while unexpected sensations, such as someone tapping you on the shoulder, grab the brain’s attention. This built-in response likely developed in early human history to detect potential predators and other threats.
Although self-tickling remains a challenge, modern science and technology have found a way to outsmart our brains. British scientists have developed a robotic solution that allows individuals to tickle themselves. This robotic tickler is operated using a remote control joystick, and a soft foam attachment delivers the tickling sensation. Even with just a fraction of a second’s delay between the person’s action and the robot’s response, subjects have reported that the sensation is remarkably similar to being tickled by another person. So, with the assistance of technology, you can, in a way, tickle yourself with a robotic partner.
In conclusion, the mystery of tickling, the science behind our laughter, and the brain’s role in distinguishing self-tickling from external tickling continue to intrigue researchers. As our understanding of these phenomena deepens, we may uncover even more fascinating insights into the human brain and its unique responses to the world around us.
Below we will look at a program in Excel VBA which creates a Userform that contains multiple pages. This userform also contains images. The Multipage Control contains two pages. At page 1, the user can fill in his/her personal information. At page 2, the user can indicate which painting he/she likes the most.
To create this Userform, execute the following steps.
1. Open the Visual Basic Editor. If the Project Explorer is not visible, click View, Project Explorer.
2. Click Insert, Userform. If the Toolbox does not appear automatically, click View, Toolbox. Your screen should be set up as below.
3. Add the Multipage control, labels, text boxes (first at the top, the second below the first), frame, option buttons (first at the left, the second at the right), list box, Image control and command button. Once this has been completed, the result should be consistent with the empty version of the Userform shown earlier. For example, create a Multipage control by clicking on Multipage from the Toolbox. Next, you can drag a Multipage control on the Userform. When you arrive at the Gender frame, remember to draw this frame first before you place the two option buttons in it.
4. You can change the names and the captions of the controls. Names are used in the Excel VBA code. Captions are those that appear on your screen. It is good practice to change the names of the controls, but it is not necessary here because we only have a few controls in this example. To change the caption of the Userform, Multipage tabs, labels, frame, option buttons and command button, click View, Properties Window and click on each control.
5. To show the Userform, place a command button on your worksheet and add the following code line:
PrivateSub CommandButton1_Click()
UserForm1.Show
EndSub
We are now going to create the Sub UserForm_Initialize. When you use the Show method for the Userform, this sub will automatically be executed.
6. Open the Visual Basic Editor.
7. In the Project Explorer, right click on UserForm1 and then click View Code.
8. Choose Userform from the left drop-down list. Choose Initialize from the right drop-down list.
The list box on page 2 will be filled. We have now created the first part of the Userform. Although it looks neat already, nothing will happen yet when we select an item from the list box or when we click on the OK button.
10. Download the images (right side of this page) and add them to “C:\test\”
11. In the Project Explorer, double click on UserForm1.
12. Double click on the list box.
13. Add the following code lines:
PrivateSub ListBox1_Click()
If ListBox1.ListIndex = 0 Then
Image1.Picture = LoadPicture(“C:\test\Mountains.jpg”) EndIf
If ListBox1.ListIndex = 1 Then
Image1.Picture = LoadPicture(“C:\test\Sunset.jpg”) EndIf
If ListBox1.ListIndex = 2 Then
Image1.Picture = LoadPicture(“C:\test\Beach.jpg”) EndIf
If ListBox1.ListIndex = 3 Then
Image1.Picture = LoadPicture(“C:\test\Winter.jpg”) EndIf
EndSub
These code lines load a picture depending on the selected item in the list box.
First, we activate Sheet1. Next, we determine emptyRow. The variable emptyRow is the first empty row and increases every time a record is added. Next, we transfer the information from the Userform to the specific columns of emptyRow. Finally, we close the Userform.
16. Exit the Visual Basic Editor, enter the labels shown below into row 1 and test the Userform.