Excel vba textbox фокус на textbox

 

Добрый день.    
Суть такова — есть форма, на ней два текстбокса, один скрыт. После внесения данных первый скрывается, второй появляется. Как сделать, что-бы фокус оказался во втором текстбоксе, а не на кнопке ОК  
Спаибо.

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

Private Sub CommandButton1_Click()  
Me.Width = 195  
TextBox2.Visible = False  
TextBox1.Visible = True  
Label1.Visible = True  
Me.TextBox1.SetFocus ‘Вот эта строка  
End Sub

 

Михаил С.

Пользователь

Сообщений: 10514
Регистрация: 21.12.2012

#4

09.03.2011 12:50:37

Спасибо, а то я вчера методом тыка искал, да так и не нашел :)

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.

userform example

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.

use setfocus in Excel to programmatically control user input

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:

  1. First, navigate to the Developer tab and click on the Visual Basic icon. This should open up the Visual Basic Editor in another window.
    open Visual Basic editor
  2. 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.
    using a userform with text input
  3. 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.
    Close button closes the userform
  4. 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.
    reset button uses setfocus button to redirect cursor back to textbox 1
  5. To test out your new scripts, you can run the current user form by clicking on the Run icon above.

  6. Excel will then run your user form.  We’ll test out our scripts by placing input into our form and clicking the Reset button.
    add input to userform with setfocus in Excel
  7. 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.
    setfocus in Excel in script associated with Reset button

Frequently Asked Questions (FAQ)

    1. 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.
    2. 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.  

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!

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:

A user form with fields

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). 

Tab order in a userform

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.

Focus on a textbox field

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:

  1. 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:
Insert label for name
  1. 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:
Change the caption of the name field
  1. Insert a label for Email address: Repeat steps 1 and 2 to create a label for Email Address.
Enter email label
  1. 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 Text boxes for Name and Email
  1. Insert the Reset button: Click on the CommandButton button from the Toolbox and drag on the form to create a button.
Create a commnad button
  1. Change the button caption: From the Properties window, set the Caption property to “Reset”. This will rewrite the button’s caption, as shown below:
Make the button Reset
  1. Insert the Close button: Repeat steps 5 and 6 to create the Close button.
Create a close button in the user form

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.

 double-click on the Close 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).

Unload the close button

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:

Double click on the Reset button

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.

Clear the Text boxes with these lines of code

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.

Setfocus VBA code to set the focus for Text Box 1

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.

  1. Click on the Run button or press F5.
Run the macro
  1. Type in a name and email address.
enter details in the text boxes
  1. Click on the form’s Reset button.
Click the 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).

Setfocus makes sure focus comes back to Name field

Once you’re done, you can close the user form by clicking on the form’s Close button.

Close the Userform

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!

Возврат фокуса в TextBox.

and_evg

Дата: Среда, 15.03.2017, 16:07 |
Сообщение № 1

Группа: Проверенные

Ранг: Обитатель

Сообщений: 416


Репутация:

72

±

Замечаний:
0% ±


Excel 2007

Всем доброго времени суток!
Столкнулся со следующей проблемой.
Имеется:

Стандартный модуль
[vba]

Код

Public myTextBox2 As MSForms.TextBox

Public Sub form2()
    UserForm2.Show
End Sub

Public Sub peredacha()
‘Это основная процедура
    If myTextBox2.Value > 5 Then
        myTextBox2.SetFocus
    End If
End Sub

[/vba]

Форма с двумя текстбоксами и двумя кнопками, ну и конечно же модуль формы
[vba]

Код

Private Sub CommandButton1_Click()
    Me.TextBox1.SetFocus
End Sub

Private Sub CommandButton2_Click()
    Call peredacha
End Sub

Private Sub TextBox1_Enter()
    Set myTextBox2 = Me.TextBox1
End Sub

[/vba]

Модуль листа
[vba]

Код

Private Sub Worksheet_Change(ByVal Target As Range)
    Call peredacha
End Sub

[/vba]

(Код МАКСИМАЛЬНО упрощен)

Так вот — Если фокус установлен в TextBox2, то код по первой кнопке
[vba]

Код

Private Sub CommandButton1_Click()
    Me.TextBox1.SetFocus
End Sub

[/vba]
отрабатывается как и полагается.

Код по второй кнопке
[vba]

Код

Private Sub CommandButton2_Click()
    Call peredacha
End Sub

[/vba]
аналогично без проблем.

но вот код повешенный на изменение листа
[vba]

Код

Private Sub Worksheet_Change(ByVal Target As Range)
    Call peredacha
End Sub

[/vba]
нивкакую не хочет возвращать фокус в TextBox1. Хотя задействована одна и та же процедура!!!

Файл прилагается.

[p.s.]P.S. Чуть не забыл (хотя это и не суть важно)…. Worksheet_Change срабатывает так как TextBox1 связан с ячейкой листа по свойству ControlSource.[/p.s.]

К сообщению приложен файл:

8890222.xls
(68.5 Kb)

 

Ответить

Perfect2You

Дата: Среда, 15.03.2017, 17:12 |
Сообщение № 2

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 237


Репутация:

59

±

Замечаний:
0% ±


Excel 2010

В том виде, что у меня Ваш файл загрузился, видно следующее:
Да, процедура -то вызывается одна, но условия в которых она запускается — две большие разницы. Когда Вы запускаете с кнопки формы, то:
1) форма уже видна
2) определена переменная, которая используется в этой процедуре.
При попытке вызвать из модуля листа ни то, ни другое не выполнено.
Приведенное ниже видоизменение процедуры на модуле листа — возможное решение проблемы.
[vba]

Код

Private Sub Worksheet_Change(ByVal Target As Range)
    Set myTextBox2 = UserForm2.TextBox1
    Call peredacha
    UserForm2.Show
End Sub

[/vba]

 

Ответить

and_evg

Дата: Среда, 15.03.2017, 18:40 |
Сообщение № 3

Группа: Проверенные

Ранг: Обитатель

Сообщений: 416


Репутация:

72

±

Замечаний:
0% ±


Excel 2007

Perfect2You,
1. Верно говорите. форма не в фокусе… почему?!?!?
2. думаю, что данная переменная публичная… действует, и в модуле листа…
3. UserForm2.Show вызывает ошибку — Форма уже отображается :(

 

Ответить

Perfect2You

Дата: Среда, 15.03.2017, 19:52 |
Сообщение № 4

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 237


Репутация:

59

±

Замечаний:
0% ±


Excel 2010

Непонятненько.
У меня как часы. Может, что-то не туда вставили? На всякий случай залью файл со своей скромной правкой.
По вопросам:

2. думаю, что данная переменная публичная… действует, и в модуле листа…

Да, обратиться к ней можно. Только чтобы значение сохранилось на все время, ее по-моему Static делать надо. А так — обратиться можно, но после работы вызвавшей программы значение теряется.

1. Верно говорите. форма не в фокусе… почему?!?!?, 3. UserForm2.Show вызывает ошибку — Форма уже отображается :(

Как я заметил: либо можно работать в форме, либо на листе. Активна форма — заблокирован лист, Активен лист — форма свернута (в памяти есть, но неактивна). Show проверяет: загружена ли? Если загружена, активирует. Если нет, то запускает.
Причем при вызове show у меня блокируется даже работа макроса из модуля листа, пока ее не закрыть. Только после этого он дорабатывает до конца. Именно поэтому в модуле листа UserForm2.Show — последний оператор. peredacha же форму не активирует — работает с любым состоянием ее: и с активным, и с фоновым.

Поэтому, исходя из моих экспериментов, получилось так…

К сообщению приложен файл:

_8890222.xls
(47.0 Kb)

Сообщение отредактировал Perfect2YouСреда, 15.03.2017, 19:59

 

Ответить

Manyasha

Дата: Среда, 15.03.2017, 22:16 |
Сообщение № 5

Группа: Модераторы

Ранг: Старожил

Сообщений: 2198


Репутация:

898

±

Замечаний:
0% ±


Excel 2010, 2016

and_evg, я так понимаю, это продолжение предыдущей темы?
Решение предложенное Wasilichем не подошло или у Вас уже просто спортивный интерес?


ЯД: 410013299366744 WM: R193491431804

 

Ответить

and_evg

Дата: Четверг, 16.03.2017, 08:14 |
Сообщение № 6

Группа: Проверенные

Ранг: Обитатель

Сообщений: 416


Репутация:

72

±

Замечаний:
0% ±


Excel 2007

Perfect2You, К сожалению в приложенном Вами файле возникает аналогичная ошибка. Правда если свойство формы ShowModal установить в False, тогда данная ошибка исчезает, но и желаемого эффекта не получаем…

Manyasha, не совсем так. Для проблемы описанной в вышеуказанной теме я применил немного переработанное Ваше решение. Хоть и пришлось многократно тиражировать код, но пришлось пока смириться. Проблема описанная в данной теме, возникла при решении следующих задач. :)

 

Ответить

Perfect2You

Дата: Четверг, 16.03.2017, 13:37 |
Сообщение № 7

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 237


Репутация:

59

±

Замечаний:
0% ±


Excel 2010

А можно поинтересоваться: как Вы переходите к работе с листом от формы? Я нажимал на крест в правом верхнем углу формы, только после этого мог вернуться на редактирование рабочего листа, а Вы?
Пробовали ли Вы что-то ввести в ячейку рабочего листа до вызова формы? В этом случае ошибка возникает?

 

Ответить

and_evg

Дата: Четверг, 16.03.2017, 14:14 |
Сообщение № 8

Группа: Проверенные

Ранг: Обитатель

Сообщений: 416


Репутация:

72

±

Замечаний:
0% ±


Excel 2007

Perfect2You,

Цитата

Я нажимал на крест в правом верхнем углу формы

Верно, только так. Просто данный пример максимально упрощен.

Цитата

В этом случае ошибка возникает?

В вашем варианте
[vba]

Код

Private Sub Worksheet_Change(ByVal Target As Range)
    Set myTextBox2 = UserForm2.TextBox1
    Call peredacha
    UserForm2.Show
End Sub

[/vba]
ошибки не возникает
А в моем
[vba]

Код

Private Sub Worksheet_Change(ByVal Target As Range)
    Call peredacha
End Sub

[/vba]
Возникает, что и логично, т.к. не определена переменная myTextBox2

 

Ответить

Perfect2You

Дата: Четверг, 16.03.2017, 14:52 |
Сообщение № 9

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 237


Репутация:

59

±

Замечаний:
0% ±


Excel 2010

Так если в моем не возникает ошибки, значит, решена проблема?

 

Ответить

and_evg

Дата: Четверг, 16.03.2017, 15:13 |
Сообщение № 10

Группа: Проверенные

Ранг: Обитатель

Сообщений: 416


Репутация:

72

±

Замечаний:
0% ±


Excel 2007

Perfect2You повторюсь

Цитата

К сожалению в приложенном Вами файле возникает аналогичная ошибка. Правда если свойство формы ShowModal установить в False, тогда данная ошибка исчезает, но и желаемого эффекта не получаем…

продолжаю биться над проблемой возврата фокуса в текстбокс формы из стандартного модуля… %)

 

Ответить

Manyasha

Дата: Четверг, 16.03.2017, 16:18 |
Сообщение № 11

Группа: Модераторы

Ранг: Старожил

Сообщений: 2198


Репутация:

898

±

Замечаний:
0% ±


Excel 2010, 2016

and_evg,
может все-таки прислушаетесь к замечаниям из прошлой темы?

Для этого есть другие способы

Я с этим полностью согласна!

Опишите задачу, что Вы пытаетесь сделать? Уверена, что есть более удобные и правильные варианты.


ЯД: 410013299366744 WM: R193491431804

 

Ответить

and_evg

Дата: Пятница, 17.03.2017, 08:28 |
Сообщение № 12

Группа: Проверенные

Ранг: Обитатель

Сообщений: 416


Репутация:

72

±

Замечаний:
0% ±


Excel 2007

Manyasha,
По поводу ControlSource начинаю тоже приходить к мнению, что преимущество ControlSource (облегчение связи поля и ячейки) нивелируется появляющимися при этом другими проблемами. Поэтому и хотелось бы услышать от авторитетных людей какие могут быть дополнительные недостатки при использовании ControlSource.

Цитата

продолжаю биться над проблемой возврата фокуса в текстбокс формы из стандартного модуля..

Все таки победил я это! :)
Может быть кому пригодится.
[vba]

Код

Public myTextBox2 As MSForms.TextBox

Public Sub peredacha()
‘Это основная процедура
    If myTextBox2.Value > 5 Then
        UserForms.Add(myTextBox2.Parent.Name).Show ‘Вот это ключевая строчка !!!
        myTextBox2.SetFocus
    End If
End Sub

[/vba]

Ну и как полагается: жду конструктивную критику :)

Сообщение отредактировал and_evgПятница, 17.03.2017, 08:30

 

Ответить

Содержание

  1. Метод TextBox.SetFocus (Access)
  2. Синтаксис
  3. Возвращаемое значение
  4. Примечания
  5. Пример
  6. Поддержка и обратная связь
  7. TextBox.SetFocus method (Access)
  8. Syntax
  9. Return value
  10. Remarks
  11. Example
  12. Support and feedback
  13. How to Use SetFocus VBA in Excel
  14. A Real Example of a Form using the SetFocus Method
  15. How to SetFocus VBA in Excel
  16. Frequently Asked Questions (FAQ)
  17. Get emails from us about Excel.
  18. SetFocus in Excel VBA – How to Use it?
  19. What Does the SetFocus Method do in Excel Forms?
  20. Why use SetFocus in Excel VBA?
  21. How to Use SetFocus in Excel VBA
  22. Creating a Sample User Form in Excel VBA
  23. Coding the Close Button
  24. Coding the Reset Button
  25. Setting Focus to the Name Field on Pressing the Reset Button
  26. Running the User Form
  27. Important Notes

Метод TextBox.SetFocus (Access)

Метод SetFocus перемещает фокус в указанную форму, указанный элемент управления в активной форме или указанное поле в активной таблице.

Синтаксис

expression. Setfocus

Выражение Переменная, представляющая объект TextBox .

Возвращаемое значение

Примечания

Используйте метод SetFocus , если требуется, чтобы для определенного поля или элемента управления был фокус, чтобы все входные данные пользователя направлялись на этот объект.

Чтобы прочитать некоторые свойства элемента управления, необходимо убедиться, что элемент управления имеет фокус. Например, текстовое поле должно иметь фокус, прежде чем вы сможете прочитать его свойство Text .

Другие свойства можно задать только в том случае, если элемент управления не имеет фокуса. Например, нельзя задать для свойств Visible или Enabled элемента управления значение False (0), если этот элемент управления имеет фокус.

Вы также можете использовать метод SetFocus для навигации в форме в соответствии с определенными условиями. Например, если пользователь выбирает Не применимо для первого из набора вопросов в форме, которая является анкетой, код Visual Basic может автоматически пропустить вопросы в этом наборе и переместить фокус на первый элемент управления в следующем наборе вопросов.

Фокус можно переместить только на видимый элемент управления или форму. Форма и элементы управления в форме не отображаются до завершения события Load формы. Поэтому при использовании метода SetFocus в событии Load формы для перемещения фокуса в эту форму необходимо использовать метод Repaint перед методом SetFocus .

Невозможно переместить фокус на элемент управления, если его свойство Enabled имеет значение False. Чтобы переместить фокус на этот элемент управления, необходимо задать для свойства Enabled значение True (1). Однако вы можете переместить фокус на элемент управления, если для его свойства Locked задано значение True.

Если форма содержит элементы управления, для которых свойство Enabled имеет значение True, вы не сможете переместить фокус на саму форму. Фокус можно перемещать только на элементы управления в форме. В этом случае, если вы попытаетесь использовать SetFocus для перемещения фокуса в форму, фокус будет установлен на элемент управления на форме, которая в последний раз получила фокус.

Используйте метод SetFocus для перемещения фокуса в подчиненную форму, которая является типом элемента управления. Вы также можете переместить фокус на элемент управления в подчиненной форме с помощью метода SetFocus дважды, переместив фокус сначала в подформу, а затем в элемент управления в подчиненной форме.

Пример

В следующем примере метод SetFocus используется для перемещения фокуса в текстовое поле EmployeeID в форме Employees .

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

TextBox.SetFocus method (Access)

The SetFocus method moves the focus to the specified form, the specified control on the active form, or the specified field on the active datasheet.

Syntax

expression.SetFocus

expression A variable that represents a TextBox object.

Return value

Use the SetFocus method when you want a particular field or control to have the focus so that all user input is directed to this object.

To read some of the properties of a control, you need to ensure that the control has the focus. For example, a text box must have the focus before you can read its Text property.

Other properties can be set only when a control doesn’t have the focus. For example, you can’t set a control’s Visible or Enabled properties to False (0) when that control has the focus.

You can also use the SetFocus method to navigate in a form according to certain conditions. For example, if the user selects Not applicable for the first of a set of questions on a form that’s a questionnaire, your Visual Basic code might then automatically skip the questions in that set and move the focus to the first control in the next set of questions.

You can move the focus only to a visible control or form. A form and controls on a form aren’t visible until the form’s Load event has finished. Therefore, if you use the SetFocus method in a form’s Load event to move the focus to that form, you must use the Repaint method before the SetFocus method.

You can’t move the focus to a control if its Enabled property is set to False. You must set a control’s Enabled property to True (1) before you can move the focus to that control. You can, however, move the focus to a control if its Locked property is set to True.

If a form contains controls for which the Enabled property is set to True, you can’t move the focus to the form itself. You can only move the focus to controls on the form. In this case, if you try to use SetFocus to move the focus to a form, the focus is set to the control on the form that last received the focus.

Use the SetFocus method to move the focus to a subform, which is a type of control. You can also move the focus to a control on a subform by using the SetFocus method twice, moving the focus first to the subform and then to the control on the subform.

Example

The following example uses the SetFocus method to move the focus to an EmployeeID text box on an Employees form.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

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)

    1. 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.
    2. 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 .

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:

  1. 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:

  1. 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:

  1. Insert a label for Email address: Repeat steps 1 and 2 to create a label for Email Address.

  1. 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.

  1. Insert the Reset button: Click on the CommandButton button from the Toolbox and drag on the form to create a button.

  1. Change the button caption: From the Properties window, set the Caption property to “Reset”. This will rewrite the button’s caption, as shown below:

  1. 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.

  1. Click on the Run button or press F5.

  1. Type in a name and email address.

  1. 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:

Источник

Like this post? Please share to your friends:
  • Excel vba textbox on enter
  • Excel vba textbox format
  • Excel vba text color
  • Excel vba workbook open method
  • Excel vba workbook names