JohnMC Пользователь Сообщений: 14 |
#1 23.11.2017 08:50:10 Приветствую всех, кто читает данную тему! Имеется вопрос по работе кнопки, добавленной просто на лист Excel (без формы) из элементов управления формы. Ситуация такова: имеются несколько процедур в VBA, которые запускаются кнопками на листе. Эти кнопки создаются с помощью кода, помещённого в модуль «ЭтаКнига» при помощи события Workbook_Open. Всё работает за исключением одной вещи: после создания кнопка оказывается выделенной рамкой и при щелчке клавишей мыши по ней вместо запуска макроса вовнутрь кнопки помещается курсор с возможностью редактирования надписи на ней. Приходится щелкать дополнительно по любой ячейке листа, чтобы снять выделение с кнопки. Существует ли команда для убирания редактируемого состояния кнопки после её создания, такая, чтобы при щелчке сразу запускался макрос? Как ни странно, нигде не нашёл ответа на этот вопрос. Создаётся впечатление, будто только у меня возникла такая проблема. Кнопка создаётся следующим образом:
Благодарю всех за помощь! |
||
Sanja Пользователь Сообщений: 14838 |
#2 23.11.2017 09:15:20 Варианты
3. Вместо кнопок используйте Автофигуры Согласие есть продукт при полном непротивлении сторон. |
||
Андрей VG Пользователь Сообщений: 11878 Excel 2016, 365 |
#3 23.11.2017 09:21:03 Доброе время суток
Чтобы не было выделения кнопки. |
||
Михаил Лебедев Пользователь Сообщений: 2856 |
#4 23.11.2017 09:50:20
Эти ТС — вааще наглость потеряли! Всё сложное — не нужно. Всё нужное — просто /М. Т. Калашников/ |
||
JohnMC Пользователь Сообщений: 14 |
#5 23.11.2017 10:36:35 Спасибо всем, кто откликнулся! Андрей VG, попробовал ваш вариант. Всё получилось, спасибо! Но есть маленькая проблемка: после создания кнопки у меня была ещё такая запись по оформлению надписи на кнопке:
Как понимаете, эта часть кода не срабатывает, так как нет объекта Selection. Как быть в этом случае? |
||
Hugo Пользователь Сообщений: 23257 |
#6 23.11.2017 10:51:51
— ну раз нет, так и не пишите
Изменено: Hugo — 23.11.2017 10:53:02 |
||||
JohnMC Пользователь Сообщений: 14 |
Спасибо всем ещё раз! Я разобрался, что нужно делать. Вариант Андрея VG подходит как нельзя лучше! Единственный вопрос, который остался — можно ли обращаться к таким кнопкам на листе по имени? Буду весьма благодарен за ответ. |
JohnMC Пользователь Сообщений: 14 |
Hugo, спасибо за вариант! Я сделал немного по-другому. Мне просто не понятно, к какому объекту относится свойство .Characters в вашем варианте… |
Hugo Пользователь Сообщений: 23257 |
#9 23.11.2017 11:03:34
— к тому, что выше по «дереву» with.
|
||||
JohnMC Пользователь Сообщений: 14 |
Hugo, честно говоря, у меня ваш вариант не прошел. VBA выдал ошибку в другом месте » Нельзя установить свойство Locked класса Range» (у меня в проге просто блокируются ячейки, которые не нужно трогать лишний раз). Не знаю, как это связано, но не суть. Я просто добавил перед каждой записью-параметра текста Код макрорекордера на имя кнопки меня немного удивил. Я сам, насколько помню, из макрорекордера код на кнопку брал. И он был основан, как я и привёл выше, на методе Add и координатах кнопки. |
Hugo Пользователь Сообщений: 23257 |
Так я взял код выделения уже ранее созданной кнопки. |
Юрий М Модератор Сообщений: 60588 Контакты см. в профиле |
JohnMC, Вам несколько раз намекнули про оформление кода. Посмотрите, как код оформлен у других и сделайте аналогично во всех своих сообщениях. Для этого ищите такую кнопку. |
JohnMC Пользователь Сообщений: 14 |
Юрий М, спасибо за подсказку. Намек-то я видел. А вот, как сделать правильно, не знал. Буду разбираться. |
Юрий М Модератор Сообщений: 60588 Контакты см. в профиле |
Немного не по теме, но про кнопки )) |
Ігор Гончаренко Пользователь Сообщений: 13746 |
#15 23.11.2017 12:09:58 как убрать фокус? а не нужно его ставить
в другом макросе, если знаете как зовут кнопку Изменено: Ігор Гончаренко — 23.11.2017 12:11:28 Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
||
JohnMC Пользователь Сообщений: 14 |
Что-то непонятное произошло с сообщением. Сам не понял, как это всё вставилось… Юрий М спросил: «Зачем вставлять кнопки программно?» Спасибо всем, кто ответил! Обнаружил много разных вариантов решения проблемы. Обязательно все испробую Изменено: JohnMC — 23.11.2017 13:05:05 |
Юрий М Модератор Сообщений: 60588 Контакты см. в профиле |
JohnMC, как понимать это Ваше сообщение? |
vikttur Пользователь Сообщений: 47199 |
#18 23.11.2017 12:35:09 Это когда руки действуют отдельно от головы |
21 / 24 / 1 Регистрация: 23.04.2012 Сообщений: 626 |
|
1 |
|
18.05.2013, 23:01. Показов 8153. Ответов 6
Итак, создал на форме TextBox, поместил в него текст. При запуске формы, тексто в нем автоматически выделяется. Подозреваю из-за того, что элементу передается фокус. как от этого избавится?
0 |
Splinter_Cell 242 / 132 / 15 Регистрация: 26.12.2012 Сообщений: 267 |
||||
18.05.2013, 23:56 |
2 |
|||
При помощи .Focus в Form_Load переустановить его на какой нибудь другой элемент. Например:
Или же пропишите свойство TabIndex для всех элементов на форме по новой, так как вам удобно…
0 |
edward_freedom 1568 / 1447 / 303 Регистрация: 01.10.2011 Сообщений: 2,636 |
||||
19.05.2013, 00:02 |
3 |
|||
1 |
3 / 3 / 0 Регистрация: 03.12.2014 Сообщений: 78 |
|
27.10.2016, 12:47 |
4 |
А как получить имя компонента, у которого на данный момент установлен фокус? То есть например по нажатии на кнопку, тому richtextbox, у которого находился фокус перед нажатием на кнопку передается какой нибудь текст
0 |
Splinter_Cell 242 / 132 / 15 Регистрация: 26.12.2012 Сообщений: 267 |
||||
27.10.2016, 13:12 |
5 |
|||
Например так:
1 |
Заблокирован |
||||
27.10.2016, 13:54 |
6 |
|||
Например так —
1 |
Заблокирован |
||||||||||||
24.12.2019, 16:10 |
7 |
|||||||||||
Тут есть два решения. Либо запретить фокус TAB:
Или же способ получше, использовать Focus(), что бы отвести фокус на главную форму, например:
Но если эти способы недоступны, вот ещё можно сделать так:
(Что-то типа ресета текстбокса
0 |
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!
When showing a userform (running its Show
method) it not only shows up on the screen but also takes the focus (the destination of e.g. keystrokes).
Say, the userform is a custom made toolbar. Its Show
fires in Workbook_Open()
but the form itself is used relatively rarely so we want the focus to go back to the main application window right after its appearance.
Unfortunately, it seems SetFocus
method is not valid for application objects.
So how is this done?
I suppose the solution for my example comes after
Private Sub Workbook_Open()
[...]
UserForm1.Show
asked Jan 20, 2015 at 10:04
i use this one :
AppActivate Application.caption
this resets the focus from a userform to your Excel Sheet.
answered Jan 21, 2015 at 17:04
2
For me
AppActivate ThisWorkbook.Application
right after the Show
statement seems to work fine.
In other cases
AppActivate "Microsoft Excel"
may also be ok.
answered Jan 20, 2015 at 10:04
GreenberetGreenberet
4801 gold badge7 silver badges18 bronze badges
2
Both AppActivate Application.Caption
and (the better) AppActivate ActiveWindow.Caption
mentioned in the other answers do their job in focusing back on the application window itself … but they do NOT focus on the actual cell/range where one typically wants the focus to be. For that, use:
ActiveCell.Activate
which has the benefit of not requiring an additional click on the cell area of the sheet where you want to return focus — an additional click that can potentially change the previous selection.
answered Dec 2, 2019 at 17:38
Yin CognytoYin Cognyto
9561 gold badge10 silver badges22 bronze badges
This is a bit tricky, but this is what can do.
In the subroutine “Private Sub UserForm_Initialize()”, add this as the last line:
Private Sub UserForm_Initialize()
. . . . . . . . . .
Application.OnTime Now(), "MoveFocusToWorksheet"
End Sub
In any of the general code modules (add one if you have none), declare an API function:
Public Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
In any of the general code modules (could be the one with the API declaration, of course), add this subroutine:
Public Sub MoveFocusToWorksheet()
Dim Dummy As Long
ThisWorkbook.Worksheets("Sheet1").Activate
' "Sheet1" here is the tab name of the sheet you want to move focus to. _
Or simply use then: With shtABC.Activate _
where "shtABC" being the worksheet's CodeName, _
same as ThisWorkbook.Worksheets("Sheet1").CodeName, _
same as the sheets module name showing in the Project Explorer panel.
Dummy = SetForegroundWindow(Application.hwnd)
End Sub
answered Jan 20, 2015 at 15:49
2
I create an object for the application e.g. Outlook, then change the WindowSate to Maximised (OlMaximized), then when I want to remove focus I minimise (olMinimized)
Set OutlookObj = GetObject(, "Outlook.Application")
OutlookObj.ActiveExplorer.WindowState = olMinimized
OutlookObj.ActiveExplorer.WindowState = olMaximized
Or you change the state from inside the application, you can also change its location and size etc for more info see: https://msdn.microsoft.com/en-us/library/office/ff838577.aspx
Application.WindowState = xlMaximized
answered May 16, 2017 at 10:12
An other form is:
AppActivate ThisWorkbook.Name
answered Mar 6, 2018 at 12:44
I use
AppActivate ActiveWindow.Caption
because
AppActivate Application.Caption
can focus the wrong window if multiple windows are opened for the same workbook.
answered Aug 6, 2019 at 19:12
CETABCETAB
212 bronze badges
As a footnote to this excellent discussion, in some circumstances you may avoid the focus problem by skipping the call to .Show
, so the focus never moves in the first place. For example with Word, if you are updating a modeless form or dialog box, just update the required area and omit the call to .Show
, e.g.:
Sub ShowProblems(ByVal ProbLoc)
EditBox2.TextBox.Text = "Here is the problem location: " & ProbLoc
' not needed: EditBox2.Show vbModeless
End Sub
answered Jan 23, 2017 at 21:08
CODE-REaDCODE-REaD
2,7293 gold badges32 silver badges60 bronze badges
Private Sub UserForm_Activate()
RefRangeIn.SetFocus
End Sub
it work for me, in excel 2013 VBA
answered Jul 17, 2017 at 7:45
Add a dummy form and add codes as below:
Private Sub SomeButton_Click()
frm_Dummy.Show vbModeless
Unload frm_Dummy
End Sub
OR
Sub SomeSub()
frm_Some.Show vbModeless
frm_Dummy.Show vbModeless
Unload frm_Dummy
End Sub
Cœur
36.7k25 gold badges191 silver badges259 bronze badges
answered Aug 20, 2017 at 17:45
I created a floating menu with a user form and use this code to make my cursor leave the user form and jump/focus back to my worksheet. It works at the end of each command button code and with the initiation code of the user form as well.
AppActivate ThisWorkbook.Application
Just place the above line of code before the «End Sub» line of any command button code and the initial show userform code.
answered Nov 5, 2018 at 4:55
First I remove control visibility by doing this:
For Each ctl In Me.MySubform.Controls
ctl.Visible = False
Next ctl
and later, I go back and bind those controls I’m going to use for the current list of fields using an array of the caption and control source name.
For i = 0 To UBound(MyArray) Step 2
Me.MySubform.Controls(i).ControlSource = MyArray(i)
Me.MySubform.Controls(i + 1).Caption = MyArray(i + 1)
Me.MySubform.Controls(i).Visible = True
Me.MySubform.Controls(i + 1).Visible = True
Next i
The issue I run into is, if a user has clicked into one of these fields providing it with focus, I seem to set the control visible property to false or rebind the field to another field during the next refresh event.
I think by removing the controls focus I would be able to accomplish this; however, I have two concerns.
- Is this possible in VBA (MS Access 2003)? If so how?
- Is there a better more ideal way to accomplish this in this environment? If so, what options are available and what considerations go into picking a solution?
Thanks,