Убрать фокус excel vba

 

JohnMC

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

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

#1

23.11.2017 08:50:10

     Приветствую всех, кто читает данную тему!

    Имеется вопрос по работе кнопки, добавленной просто на лист Excel (без формы) из элементов управления формы.

    Ситуация такова: имеются несколько процедур в VBA, которые запускаются кнопками на листе. Эти кнопки создаются с помощью кода, помещённого в модуль «ЭтаКнига» при помощи события Workbook_Open. Всё работает за исключением одной вещи: после создания кнопка оказывается выделенной рамкой и при щелчке клавишей мыши по ней вместо запуска макроса вовнутрь кнопки помещается курсор с возможностью редактирования надписи на ней. Приходится щелкать дополнительно по любой ячейке листа, чтобы снять выделение с кнопки. Существует ли команда для убирания редактируемого состояния кнопки после её создания, такая, чтобы при щелчке сразу запускался макрос?

Как ни странно, нигде не нашёл ответа на этот вопрос. Создаётся впечатление, будто только у меня возникла такая проблема.

Кнопка создаётся следующим образом:

Код
This Workbook.Worksheets (" Лист1").Buttons.Add (690, 250, 240, 25).Select
With Selection
    .Name = "ISO_DRAWING_BUTTON"
    .OnAction = "ISO_DRAWING_FILE"
    .Characters.Text = "Создание ссылок на чертежах"
End With

Благодарю всех за помощь!

 

Sanja

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

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

#2

23.11.2017 09:15:20

Варианты
1. После создания кнопки программно выделяйте любую ячейку
2. Попробуйте такой код

Код
Application.CommandBars.FindControl(ID:=1605).Reset

3. Вместо кнопок используйте Автофигуры

Согласие есть продукт при полном непротивлении сторон.

 

Андрей VG

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

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

Excel 2016, 365

#3

23.11.2017 09:21:03

Доброе время суток
Sanja, коллега там всё же приведён код, не связанный с кнопками панелей инструментов. Просто ТС нагло ленится оформить код, поэтому он не читаем. Достаточно написать

Код
With his Workbook.Worksheets (" Лист1").Buttons.Add (690, 250, 240, 25)

Чтобы не было выделения кнопки.

 

Михаил Лебедев

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

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

#4

23.11.2017 09:50:20

Цитата
Андрей VG написал:
Просто ТС нагло ленится оформить код

Эти ТС — вааще наглость потеряли! :)

Всё сложное — не нужно. Всё нужное — просто /М. Т. Калашников/

 

JohnMC

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

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

#5

23.11.2017 10:36:35

Спасибо всем, кто откликнулся!
Насчёт того, что «Просто ТС нагло ленится оформить код». Это не так. Так как сижу в форуме с телефона, то код писал вручную, а это, как сами понимаете не проще, чем скопировать из редактора. Просто, если честно, я понятия не имею, как нужно оформлять код. Уж извините.

Андрей VG, попробовал ваш вариант. Всё получилось, спасибо! Но есть маленькая проблемка: после создания кнопки у меня была ещё такая запись по оформлению надписи на кнопке:

Код
With Selection.Characters(Start:=1, Length:=37).Font
        .Name = "Calibri"
        .FontStyle = "Regular"
        .Size =10
End With

Как понимаете, эта часть кода не срабатывает, так как нет объекта  Selection. Как быть в этом случае?
Простите, что код по-прежнему не оформлен )

 

Hugo

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

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

#6

23.11.2017 10:51:51

Цитата
JohnMC написал:
так как нет объекта  Selection

— ну раз нет, так и не пишите :)
Вот прямо так буквально — уберите это слово.

Код
With ThisWorkbook.Worksheets("Лист1").Buttons.Add(690, 250, 240, 25)
    .Name = "ISO_DRAWING_BUTTON"
    .OnAction = "ISO_DRAWING_FILE"
    .Characters.Text = "Создание ссылок на чертежах"
    
    With .Characters(Start:=1, Length:=37).Font
           .Name = "Calibri"
           .FontStyle = "Regular"
           .Size = 10
    End With
    
End With

Изменено: Hugo23.11.2017 10:53:02

 

JohnMC

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

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

Спасибо всем ещё раз! Я разобрался, что нужно делать. Вариант Андрея VG подходит как нельзя лучше!
Просто добавил код для оформления текста в блок With — End With.

Единственный вопрос, который остался — можно ли обращаться к таким кнопкам на листе по имени? Буду весьма благодарен за ответ.

 

JohnMC

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

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

Hugo, спасибо за вариант! Я сделал немного по-другому. Мне просто не понятно, к какому объекту относится свойство .Characters в вашем варианте…

 

Hugo

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

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

#9

23.11.2017 11:03:34

Цитата
JohnMC написал:
к какому объекту относится свойство .Characters в вашем варианте..

— к тому, что выше по «дереву» with.
Про имя — рекордер записал так6

Код
 ActiveSheet.Shapes.Range(Array("ISO_DRAWING_BUTTON")).Select
 

JohnMC

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

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

Hugo, честно говоря, у меня ваш вариант не прошел. VBA выдал ошибку в другом месте » Нельзя установить свойство  Locked класса Range» (у меня в проге просто блокируются ячейки, которые не нужно трогать лишний раз). Не знаю, как это связано, но не суть. Я просто добавил перед каждой записью-параметра текста
«.Characters ( Start:=1, Length:=37).Font»

Код макрорекордера на имя кнопки меня немного удивил. Я сам, насколько помню, из макрорекордера код на кнопку брал. И он был основан, как я и привёл выше, на методе Add и координатах кнопки.
Попробую, то, что вы написали, возможно подойдет )

 

Hugo

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

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

Так я взял код выделения уже ранее созданной кнопки.

 

Юрий М

Модератор

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

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

JohnMC, Вам несколько раз намекнули про оформление кода. Посмотрите, как код оформлен у других и сделайте аналогично во всех своих сообщениях. Для этого ищите такую кнопку.

 

JohnMC

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

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

Юрий М, спасибо за подсказку. Намек-то я видел. А вот, как сделать правильно, не знал. Буду разбираться.

 

Юрий М

Модератор

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

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

Немного не по теме, но про кнопки ))
А зачем её программно создавать? Заготовить заранее, и пусть живёт на листе.

 

Ігор Гончаренко

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

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

#15

23.11.2017 12:09:58

как убрать фокус? а не нужно его ставить

Код
set MyButt = Workbook.Worksheets ("Лист1").Buttons.Add (690, 250, 240, 25)
' а потом уже
  MyButt.Name = "ISO_DRAWING_BUTTON" 
  MyButt.OnAction = "ISO_DRAWING_FILE" 
  MyButt ...

в другом макросе, если знаете как зовут кнопку
 set MyButt = activesheet.shapes(«ISO_DRAWING_BUTTON»)
 смотрите свойства MyButt и доступаетесь к тем, что Вам нужны

Изменено: Ігор Гончаренко23.11.2017 12:11:28

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

JohnMC

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

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

Что-то непонятное произошло с сообщением. Сам не понял, как это всё вставилось…

Юрий М спросил: «Зачем вставлять кнопки программно?»
Суть в том, чтобы при запуске файла появлялось что-то вроде меню: 2 кнопки («Редактирование файла расчетной модели» и «Создание ссылок на чертежах»), которые должны запустить несколько разных процедур. Делать ради этого форму смысла не вижу. При этом при нажатии каждой из кнопок запускаются отдельные макросы, которые создают другие кнопки для дальнейшей работы с ними. Оставлять при этом начальные кнопки было бы нецелесообразно, поэтому, они удаляются до тех пор, пока пользователь снова не выйдет в главное меню.

Спасибо всем, кто ответил! Обнаружил много разных вариантов решения проблемы. Обязательно все испробую :-)

Изменено: JohnMC23.11.2017 13:05:05

 

Юрий М

Модератор

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

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

JohnMC, как понимать это Ваше сообщение?

 

vikttur

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

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

#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 переустановить его на какой нибудь другой элемент. Например:

VB.NET
1
Button1.Focus()

Или же пропишите свойство TabIndex для всех элементов на форме по новой, так как вам удобно…



0



edward_freedom

1568 / 1447 / 303

Регистрация: 01.10.2011

Сообщений: 2,636

19.05.2013, 00:02

3

VB.NET
1
TextBox1.TabStop = False



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

Например так:

VB.NET
1
Dim MyCntrlName As String = ActiveControl.Name



1



Shersh

Заблокирован

27.10.2016, 13:54

6

Например так —

VB.NET
1
2
3
4
5
6
7
8
9
Public Class FMSfrm
  Dim lastRTB As RichTextBox
  Private Sub RTB_Leave(RTB As RichTextBox, e As EventArgs) Handles RichTextBox1.Leave, RichTextBox2.Leave
    lastRTB = RTB
  End Sub
  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    lastRTB.Text = Now
  End Sub
End Class



1



713881399

Заблокирован

24.12.2019, 16:10

7

Тут есть два решения.

Либо запретить фокус TAB:

VB.NET
1
Textbox1.TabStop = False

Или же способ получше, использовать Focus(), что бы отвести фокус на главную форму, например:

VB.NET
1
Me.Focus()

Но если эти способы недоступны, вот ещё можно сделать так:

VB.NET
1
2
Textbox1.Enable = False
Textbox1.Enable = True

(Что-то типа ресета текстбокса , ну конечно там ни к чему эти костыли, но всё же рабочий же способ)



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:

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!

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

Greenberet's user avatar

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

Patrick Lepelletier's user avatar

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

Greenberet's user avatar

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 Cognyto's user avatar

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

Gene Skuratovsky's user avatar

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

Andrew J Martin's user avatar

An other form is:

AppActivate ThisWorkbook.Name

answered Mar 6, 2018 at 12:44

Riccardo La Marca's user avatar

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

CETAB's user avatar

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-REaD's user avatar

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

Carlosmuerto's user avatar

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's user avatar

Cœur

36.7k25 gold badges191 silver badges259 bronze badges

answered Aug 20, 2017 at 17:45

Fen's user avatar

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

Geo Matrix's user avatar

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.

  1. Is this possible in VBA (MS Access 2003)? If so how?
  2. 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,

Понравилась статья? Поделить с друзьями:
  • Убрать пароль с листа excel онлайн
  • Убрать фильтр в excel горячая клавиша
  • Убрать пароль на макрос excel
  • Убрать фиксацию ячейки в excel
  • Убрать пароль в excel 2019 excel