User forms in Excel usually have a particular ‘tab order’ that automatically navigates you to a given control as and when you enter data.
However, sometimes you might want to override this order to ensure that a specific control gets ‘focus’ at a given instance.
For example, you may want the cursor to automatically come to a specific text box so that you don’t have to manually select the text box before typing.
The VBA SetFocus method helps you do just that.
In this tutorial, we will discuss the SetFocus method in detail, including why they are used and how to use them.
What Does the SetFocus Method do in Excel Forms?
The SetFocus method helps shift the focus to a specific form, control, or field. The syntax for this function is:
Expression.SetFocus
Here, expression is the expression that returns a command object.
The SetFocus function is usually used when you want a particular field or control to have the focus, thereby directing the user’s input to that field/control.
For example, consider the following user form:
If you look at the Tab order for this form (by selecting View->Tab order), you will see that TextBox1 (the input box corresponding to the Name field) comes first (It is the first input box in the list).
This means that as soon as the form opens, the focus goes to this input box (shown by the cursor blinking in this box), letting you enter your first input there.
The Reset button in this form is meant to simply clear all inputs in the text boxes (in case the user makes a mistake), allowing you to re-enter data into these fields.
However, since the tab order of CommandButton2 (the Close button) comes after that of CommandButton1 (the Reset button), the form’s focus will move to the Close button after the user presses the Reset button.
But this is not what we usually want.
Generally, we would prefer to have the focus return to TextBox1 (the Name input field) after clicking Reset, so that the user can re-enter data without having to explicitly click into the box (or press the tab key several times).
This is where the SetFocus method comes in handy.
Using this method, we can easily dictate which form control we want our focus to be on at any point, while the user form is running.
How to Use SetFocus in Excel VBA
Let us create a simple form to understand how and when the SetFocus method is applicable.
Creating a Sample User Form in Excel VBA
To create the form, you need to be in the Visual Basic window (by navigating to Developer->Visual Basic).
Once you’re in, follow the steps shown below to create a very simple user form, that accepts a user’s Name and Email address:
- Insert a label for Name: Click on the Label button from the userForm Toolbox and drag on the User form to create the label, as shown below:
- Change the label caption: From the Properties window (on the left sidebar), set the Caption property to “Name:”. This will rewrite the label’s caption, as shown below:
- Insert a label for Email address: Repeat steps 1 and 2 to create a label for Email Address.
- Insert text boxes to receive name and email address inputs: Click on the Textbox button from the UserForm Toolbox and drag on the User form to create the input text box. Do this twice to create TextBox1 for the name input and TextBox2 for the email address input.
- Insert the Reset button: Click on the CommandButton button from the Toolbox and drag on the form to create a button.
- Change the button caption: From the Properties window, set the Caption property to “Reset”. This will rewrite the button’s caption, as shown below:
- Insert the Close button: Repeat steps 5 and 6 to create the Close button.
Your User form’s interface is now ready.
Coding the Close Button
Now we need to code the buttons to perform appropriate actions. We want the form to close when the Close button is pressed.
For this, double-click on the Close button. It opens the Code window, where you can see the procedure created for the button.
Enter the following line of code right after the first line:
Unload Me
The above line will unload your form when the Close button is pressed (which means it will close the user form).
Close the Code window.
Coding the Reset Button
When the Reset button is clicked, we want both input boxes cleared out, so that the user can provide fresh input.
Double click on the Reset button to open the Code window:
Enter the following lines of code right after the first line (Private Sub CommandButton1_Click()):
TextBox1=""
TextBox2=""
These two lines simply replace the contents of TextBox1 and TextBox2 with blanks.
Setting Focus to the Name Field on Pressing the Reset Button
We are still not done yet.
Once your input boxes are cleared, we want the focus to return to TextBox1 (the Name field).
And this is where we will be using the SetFocus method in Excel VBA.
For this, insert the following line:
TextBox1.SetFocus
Here we simply used the SetFocus function on the handle returned by TextBox1 to set the focus to this control.
Close the Code window.
In the above three-line code for the Reset button (Command_Button1), we first asked it to remove anything that’s already there in the two text fields (TextBox1 and TextBox2), and then move the focus to TextBox1. Now, when you press the reset button, it will first clear the text fields and then bring your cursor to the first text box
Running the User Form
It’s now time to test out our User Form and all the coding we did so far.
- Click on the Run button or press F5.
- Type in a name and email address.
- Click on the form’s Reset button.
Notice that the inputs you had entered into both text boxes have been cleared.
You should also notice a blinking cursor at the first input box (TextBox1), showing that the focus is now on this field, allowing you to type in the new name directly (without having to press the tab or click inside the textbox).
Once you’re done, you can close the user form by clicking on the form’s Close button.
Note that this tutorial was simply meant to help you understand the SetFocus method.
We did not connect the sample user form to any cell in the Excel worksheet, as that would go beyond the scope of the tutorial.
However, you can go ahead and further refine the form as you like.
Important Notes
There are a few things that you should keep in mind when using the SetFocus method in Excel VBA:
- You can only set focus on a single control at a time (this of course goes without saying).
- A textbox has to have the focus on itself before you can read any of its Text properties.
- You cannot set other properties of a control when it has the focus. For example, you cannot set/change the Visible or Enabled properties of an input box when it is in focus.
The SetFocus method is commonly used in Excel VBA.
In this tutorial, we explained what the SetFocus method does and how to apply it to a user form in Excel. We hope you found the tutorial informative and useful.
Other Excel tutorials you may also find useful:
- What is the Excel Personal Workbook Location?
- Using Application.GetSaveAsFilename in VBA in Excel (Examples)
- Using Application.EnableEvents in VBA in Excel (Explained with Examples)
- How to Remove Macros from Excel? 3 Simple Methods
- What is an Active Cell in Excel?
- Subscript Out of Range Error in VBA – How to Fix!
The SetFocus method in Excel VBA is useful when you need to program the user’s cursor to focus on a specific control in a user form.
This function is usually used when you want to direct the user’s input to a specific part of a form.
Let’s take a look at a sample use case for the SetFocus method in Excel.
Suppose you have a user form with the required fields. If the user tries to click the Submit button with missing data on the required fields, you want their cursor to focus on the first required field they’ve missed automatically. How can we do this using Excel VBA?
The SetFocus method redirects the user’s cursor to focus on a specific control in the field. In the example above, if our required field is an object called TextBox_username, then adding the command TextBox_username.SetFocus
will make this object the next object of focus.
This use case is just one way to use the SetFocus VBA function in Excel. In the next section, we’ll look into an even simpler application for the SetFocus method.
Now that we know when to use the SetFocus VBA function, let’s dive into how users can apply it on their Excel user forms.
A Real Example of a Form using the SetFocus Method
Let’s take a look at a real example of an Excel user form that uses the SetFocus VBA method.
The user form seen below is designed to prompt the user for their email address and organization details. Included in the form are two command buttons. If the user clicks on the ‘Close’ button, the user form will close. When the user clicks on the ‘Reset’ button, both text fields will clear, and the user is free to fill-up the form again.
If we look at the scripts added to the Reset button, you’ll notice that the SetFocus method was used after clearing out the two textboxes.
If we did not add a SetFocus method, the user would have to click on the first textbox to begin input manually. Using the SetFocus function streamlines the form’s user experience.
You can make your own copy of the spreadsheet above using the link attached below. Download the workbook and open it in your Excel Desktop application to access the sample user form.
If you’re ready to try out the SetFocus function in Excel, let’s begin writing it ourselves!
This section will explain each step needed to use the SetFocus VBA method in Excel. You’ll learn how to add the method to a command button so that the user’s cursor is redirected when the button is clicked on.
In this example, we’ll use a sample user form that asks the user for their email address and organization. We’ll use the SetFocus method to redirect the user’s cursor to the email address field if the user chooses to reset the form.
Follow these steps to start adding the SetFocus function to your user forms:
- First, navigate to the Developer tab and click on the Visual Basic icon. This should open up the Visual Basic Editor in another window.
- In the Visual Basic Editor, you can control what your user forms look like. You can also add custom VBA scripts to any control placed in your form. In this example, we’ll add custom code to our Reset and Close buttons.
- Double-click on the ‘Close’ button to open up the code editor. In this example, we’ll add the command ‘Unload Me’ to exit the form when we click this button.
- In the editor for the ‘Reset’ button, we’ll set the values of the two text boxes to empty strings. Next, we’ll use the SetFocus method to place the user’s cursor on TextBox1.
- To test out your new scripts, you can run the current user form by clicking on the Run icon above.
- Excel will then run your user form. We’ll test out our scripts by placing input into our form and clicking the Reset button.
- When the Reset button is placed, both fields are cleared out, and the user’s blinking cursor is focused on the email address field. The user is now free to type in their email address directly without using the Tab key or clicking on the textbox itself.
Frequently Asked Questions (FAQ)
-
- Can I change other properties of a control when it has the focus?
Excel does not allow you to set the properties of a control when it is in focus. For example, we cannot change the Enabled property of a control if the user is currently focused on that control. - Can I set focus to a control that is not visible or enabled?
You can only move focus to a visible control. The control must also have their Enabled property set to True.
- Can I change other properties of a control when it has the focus?
This step-by-step guide should be all you need to start using the SetFocus method in your Excel user forms. Our guide shows how easy it is to direct user input programmatically using VBA.
The SetFocus VBA method is just one of many functions available in Excel’s Visual Basic Editor. With so many other Excel functions available, you can surely find one that suits your use case.
Are you interested in learning more about what Excel can do? Subscribe to our newsletter to learn about the latest Excel guides and tutorials from us.
Get emails from us about Excel.
Our goal this year is to create lots of rich, bite-sized tutorials for Excel users like you. If you liked this one, you’d love what we are working on! Readers receive ✨ early access ✨ to new content.
Hi! I’m a Software Developer with a passion for data analytics. Google Sheets has helped me empower my teams to make data-driven decisions. There’s always something new to learn, so let’s explore how you can make life so much easier with spreadsheets!
Добрый день. |
|
vikttur Пользователь Сообщений: 47199 |
|
Юрий М Модератор Сообщений: 60575 Контакты см. в профиле |
Private Sub CommandButton1_Click() |
Михаил С. Пользователь Сообщений: 10514 |
#4 09.03.2011 12:50:37 Спасибо, а то я вчера методом тыка искал, да так и не нашел |
- Remove From My Forums
-
Question
-
How do I set focus to a Cell. For Example I keep the cell G7 active and Close the Excel sheet. While I am opening it should set focus on D4. How is this possible
I have tried the Following but none works.
ActiveSheet.Cells(5, 4).Select
-or-
ActiveSheet.Range("D5").Select
-
Edited by
Tuesday, September 6, 2011 2:36 PM
-
Edited by
Answers
-
How do I set focus to a Cell. For Example I keep the cell G7 active and Close the Excel sheet. While I am opening it should set focus on D4. How is this possible
I have tried the Following but none works.
ActiveSheet.Cells(5, 4).Select
-or-
ActiveSheet.Range("D5").Select
Ram, it depends where are you calling that code from
Place the code in the workbook open event
Option Explicit Private Sub Workbook_Open() ActiveSheet.Range("D5").Select '<~~ Change it to D4 if you want D4 to become Active End Sub
See the image attached.
Also ensure that the macros are enabled
Sid (A good exercise for the Heart is to bend down and help another up) Please do not email me your questions. I do not answer questions by email unless I get paid for it If you want, create a thread in Excel forum and email me the link and I will help you
if I can.-
Edited by
Siddharth Rout
Wednesday, September 7, 2011 6:48 AM -
Marked as answer by
Calvin_Gao
Wednesday, September 7, 2011 10:00 AM -
Unmarked as answer by
Calvin_Gao
Wednesday, September 7, 2011 10:00 AM -
Proposed as answer by
Calvin_Gao
Wednesday, September 7, 2011 10:00 AM -
Marked as answer by
Calvin_Gao
Wednesday, September 14, 2011 5:50 AM
-
Edited by
Содержание
- How to Use SetFocus VBA in Excel
- A Real Example of a Form using the SetFocus Method
- How to SetFocus VBA in Excel
- Frequently Asked Questions (FAQ)
- Get emails from us about Excel.
- SetFocus in Excel VBA – How to Use it?
- What Does the SetFocus Method do in Excel Forms?
- Why use SetFocus in Excel VBA?
- How to Use SetFocus in Excel VBA
- Creating a Sample User Form in Excel VBA
- Coding the Close Button
- Coding the Reset Button
- Setting Focus to the Name Field on Pressing the Reset Button
- Running the User Form
- Important Notes
How to Use SetFocus VBA in Excel
The SetFocus method in Excel VBA is useful when you need to program the user’s cursor to focus on a specific control in a user form.
This function is usually used when you want to direct the user’s input to a specific part of a form.
Table of Contents
Let’s take a look at a sample use case for the SetFocus method in Excel.
Suppose you have a user form with the required fields. If the user tries to click the Submit button with missing data on the required fields, you want their cursor to focus on the first required field they’ve missed automatically. How can we do this using Excel VBA?
The SetFocus method redirects the user’s cursor to focus on a specific control in the field. In the example above, if our required field is an object called TextBox_username, then adding the command TextBox_username.SetFocus will make this object the next object of focus.
This use case is just one way to use the SetFocus VBA function in Excel. In the next section, we’ll look into an even simpler application for the SetFocus method.
Now that we know when to use the SetFocus VBA function, let’s dive into how users can apply it on their Excel user forms.
A Real Example of a Form using the SetFocus Method
Let’s take a look at a real example of an Excel user form that uses the SetFocus VBA method.
The user form seen below is designed to prompt the user for their email address and organization details. Included in the form are two command buttons. If the user clicks on the ‘Close’ button, the user form will close. When the user clicks on the ‘Reset’ button, both text fields will clear, and the user is free to fill-up the form again.
If we look at the scripts added to the Reset button, you’ll notice that the SetFocus method was used after clearing out the two textboxes.
If we did not add a SetFocus method, the user would have to click on the first textbox to begin input manually. Using the SetFocus function streamlines the form’s user experience.
You can make your own copy of the spreadsheet above using the link attached below. Download the workbook and open it in your Excel Desktop application to access the sample user form.
If you’re ready to try out the SetFocus function in Excel, let’s begin writing it ourselves!
How to SetFocus VBA in Excel
This section will explain each step needed to use the SetFocus VBA method in Excel. You’ll learn how to add the method to a command button so that the user’s cursor is redirected when the button is clicked on.
In this example, we’ll use a sample user form that asks the user for their email address and organization. We’ll use the SetFocus method to redirect the user’s cursor to the email address field if the user chooses to reset the form.
Follow these steps to start adding the SetFocus function to your user forms:
- First, navigate to the Developer tab and click on the Visual Basic icon. This should open up the Visual Basic Editor in another window.
Frequently Asked Questions (FAQ)
-
- Can I change other properties of a control when it has the focus?
Excel does not allow you to set the properties of a control when it is in focus. For example, we cannot change the Enabled property of a control if the user is currently focused on that control. - Can I set focus to a control that is not visible or enabled?
You can only move focus to a visible control. The control must also have their Enabled property set to True .
- Can I change other properties of a control when it has the focus?
This step-by-step guide should be all you need to start using the SetFocus method in your Excel user forms. Our guide shows how easy it is to direct user input programmatically using VBA.
The SetFocus VBA method is just one of many functions available in Excel’s Visual Basic Editor. With so many other Excel functions available, you can surely find one that suits your use case.
Are you interested in learning more about what Excel can do? Subscribe to our newsletter to learn about the latest Excel guides and tutorials from us.
Get emails from us about Excel.
Our goal this year is to create lots of rich, bite-sized tutorials for Excel users like you. If you liked this one, you’d love what we are working on! Readers receive ✨ early access ✨ to new content.
Источник
SetFocus in Excel VBA – How to Use it?
User forms in Excel usually have a particular ‘tab order’ that automatically navigates you to a given control as and when you enter data.
However, sometimes you might want to override this order to ensure that a specific control gets ‘focus’ at a given instance.
For example, you may want the cursor to automatically come to a specific text box so that you don’t have to manually select the text box before typing.
The VBA SetFocus method helps you do just that.
In this tutorial, we will discuss the SetFocus method in detail, including why they are used and how to use them.
Table of Contents
What Does the SetFocus Method do in Excel Forms?
The SetFocus method helps shift the focus to a specific form, control, or field. The syntax for this function is:
Here, expression is the expression that returns a command object.
Why use SetFocus in Excel VBA?
The SetFocus function is usually used when you want a particular field or control to have the focus, thereby directing the user’s input to that field/control.
For example, consider the following user form:
If you look at the Tab order for this form (by selecting View->Tab order), you will see that TextBox1 (the input box corresponding to the Name field) comes first (It is the first input box in the list).
This means that as soon as the form opens, the focus goes to this input box (shown by the cursor blinking in this box), letting you enter your first input there.
The Reset button in this form is meant to simply clear all inputs in the text boxes (in case the user makes a mistake), allowing you to re-enter data into these fields.
However, since the tab order of CommandButton2 (the Close button) comes after that of CommandButton1 (the Reset button), the form’s focus will move to the Close button after the user presses the Reset button.
But this is not what we usually want.
Generally, we would prefer to have the focus return to TextBox1 (the Name input field) after clicking Reset, so that the user can re-enter data without having to explicitly click into the box (or press the tab key several times).
This is where the SetFocus method comes in handy.
Using this method, we can easily dictate which form control we want our focus to be on at any point, while the user form is running.
How to Use SetFocus in Excel VBA
Let us create a simple form to understand how and when the SetFocus method is applicable.
Creating a Sample User Form in Excel VBA
To create the form, you need to be in the Visual Basic window (by navigating to Developer->Visual Basic).
Once you’re in, follow the steps shown below to create a very simple user form, that accepts a user’s Name and Email address:
- Insert a label for Name: Click on the Label button from the userForm Toolbox and drag on the User form to create the label, as shown below:
- Change the label caption: From the Properties window (on the left sidebar), set the Caption property to “Name:”. This will rewrite the label’s caption, as shown below:
- Insert a label for Email address: Repeat steps 1 and 2 to create a label for Email Address.
- Insert text boxes to receive name and email address inputs: Click on the Textbox button from the UserForm Toolbox and drag on the User form to create the input text box. Do this twice to create TextBox1 for the name input and TextBox2 for the email address input.
- Insert the Reset button: Click on the CommandButton button from the Toolbox and drag on the form to create a button.
- Change the button caption: From the Properties window, set the Caption property to “Reset”. This will rewrite the button’s caption, as shown below:
- Insert the Close button: Repeat steps 5 and 6 to create the Close button.
Your User form’s interface is now ready.
Coding the Close Button
Now we need to code the buttons to perform appropriate actions. We want the form to close when the Close button is pressed.
For this, double-click on the Close button. It opens the Code window, where you can see the procedure created for the button.
Enter the following line of code right after the first line:
The above line will unload your form when the Close button is pressed (which means it will close the user form).
Close the Code window.
Coding the Reset Button
When the Reset button is clicked, we want both input boxes cleared out, so that the user can provide fresh input.
Double click on the Reset button to open the Code window:
Enter the following lines of code right after the first line (Private Sub CommandButton1_Click()):
These two lines simply replace the contents of TextBox1 and TextBox2 with blanks.
Setting Focus to the Name Field on Pressing the Reset Button
We are still not done yet.
Once your input boxes are cleared, we want the focus to return to TextBox1 (the Name field).
And this is where we will be using the SetFocus method in Excel VBA.
For this, insert the following line:
Here we simply used the SetFocus function on the handle returned by TextBox1 to set the focus to this control.
Close the Code window.
In the above three-line code for the Reset button (Command_Button1), we first asked it to remove anything that’s already there in the two text fields (TextBox1 and TextBox2), and then move the focus to TextBox1. Now, when you press the reset button, it will first clear the text fields and then bring your cursor to the first text box
Running the User Form
It’s now time to test out our User Form and all the coding we did so far.
- Click on the Run button or press F5.
- Type in a name and email address.
- Click on the form’s Reset button.
Notice that the inputs you had entered into both text boxes have been cleared.
You should also notice a blinking cursor at the first input box (TextBox1), showing that the focus is now on this field, allowing you to type in the new name directly (without having to press the tab or click inside the textbox).
Once you’re done, you can close the user form by clicking on the form’s Close button.
Note that this tutorial was simply meant to help you understand the SetFocus method.
We did not connect the sample user form to any cell in the Excel worksheet, as that would go beyond the scope of the tutorial.
However, you can go ahead and further refine the form as you like.
Important Notes
There are a few things that you should keep in mind when using the SetFocus method in Excel VBA:
- You can only set focus on a single control at a time (this of course goes without saying).
- A textbox has to have the focus on itself before you can read any of its Text properties.
- You cannot set other properties of a control when it has the focus. For example, you cannot set/change the Visible or Enabled properties of an input box when it is in focus.
The SetFocus method is commonly used in Excel VBA.
In this tutorial, we explained what the SetFocus method does and how to apply it to a user form in Excel. We hope you found the tutorial informative and useful.
Other Excel tutorials you may also find useful:
Источник