Vba фокус на ячейку excel

  • 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

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

Леонид1

1 / 1 / 0

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

Сообщений: 69

1

Передача фокуса определенной ячейке

26.10.2011, 10:24. Показов 12559. Ответов 8

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Какой код написать в кнопке чтобы перемещаться в определенную ячейку определенного листа?
Вот так не работает:

Visual Basic
1
2
3
4
Private Sub CommandButton1_Click()
Sheets("Лист2").Select
    Range("C1").Select
End Sub



0



1562 / 1114 / 165

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

Сообщений: 6,454

26.10.2011, 10:29

2

Не верю (с)
Как именно «не работает»?



0



1 / 1 / 0

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

Сообщений: 69

26.10.2011, 10:30

 [ТС]

3

Runtime error 1004
метод select из класса Range завершен неверно



0



1562 / 1114 / 165

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

Сообщений: 6,454

26.10.2011, 10:33

4

Проверь Range(«C1») ,букву С — может русскую вписал. Ибо код 100% работоспособен



0



Казанский

15136 / 6410 / 1730

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

Сообщений: 9,999

26.10.2011, 10:33

5

Цитата
Сообщение от pincet
Посмотреть сообщение

Не верю (с)

А я верю

Visual Basic
1
2
3
4
Private Sub CommandButton1_Click()
Sheets("Лист2").Select
Sheets("Лист2").Range("C1").Select
End Sub

В модуле листа

свойства Range, Cells и т.д. без явного указания листа, относятся к Me, т.е. к этому листу, а не к ActiveSheet.



1



pincet

1562 / 1114 / 165

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

Сообщений: 6,454

26.10.2011, 10:34

6

Visual Basic
1
2
3
4
5
Sub Кнопка1_Щелчок()
Sheets(1).Select
Range("с1").Select
 
End Sub



1



Апострофф

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

26.10.2011, 10:34

7

Или листа «Лист2» нет?



0



1562 / 1114 / 165

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

Сообщений: 6,454

26.10.2011, 10:39

8

Кстати, кнопка где лежит? На листе али на форме какой?
Если на форме, то Казанский из райт.



0



1 / 1 / 0

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

Сообщений: 69

26.10.2011, 10:41

 [ТС]

9

просто на листе, но Казанский вроде бы действительно прав, потому что с его изменениями код работает…
спасибо все заработало!



0



Should be a simple question:

I have the following script which pastes data:

Dim a As Range
Set a = Selection
Selection.Cut
Range("C1:I1").End(xlDown).Offset(1, 0).Select
ActiveSheet.Paste

Upon pasting, the ActiveSheet moves to the cell in which its pasting in. How do I re-focus on the cell from which the data was cut?

I want to put the focus on the Range that is currently held in the ‘A’ variable.

I tried this:

a.Select

And

a.Activate

but, it doesn’t actually move the activeSheet to the correct area; it just selects it.

pnuts's user avatar

pnuts

58k11 gold badges85 silver badges137 bronze badges

asked Jan 24, 2013 at 17:51

Parseltongue's user avatar

ParseltongueParseltongue

11k28 gold badges90 silver badges157 bronze badges

What you seem to want can be accomplished in a single line:

Sub OneLiner()
   Selection.Cut Range("C1:I1").End(xlDown).Offset(1, 0)
End Sub

A single space after the cut keyword means the destination follows.

There’s no need to Dim or Set a, as you’re not even using a as a variable in your code.

Doing it this way does not use the clipboard, change the position of the cursor or page location.

answered Jan 24, 2013 at 18:18

tbur's user avatar

1

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!

Перенос фокуса с курсора мыши на активную ячейку

Alex59

Дата: Вторник, 19.02.2019, 10:41 |
Сообщение № 1

Группа: Пользователи

Ранг: Прохожий

Сообщений: 2


Репутация:

0

±

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


Excel 2003

Здравствуйте.
Помогите решить проблему (не комфортность).
Описание:
1. Есть книга с 3-мя листами:

  • лист «Таблица» — заполняется переменной информацией. Имеет ключевые поля в колонке «А»
  • лист «Выборка» — при вводе номера ключевого поля в ячейку «А1», выполняется выборка инфы из листа «Таблица» и некая ее обработка
  • лист «Бланк» — бланк документа, заполняется обработанной инфой из листа «Выборка»

2. На листе «Таблица» имеется кнопка «Печать», при нажатии мышью на которую выполняются след. действия:

  • из строки, где находится активная ячейка выбирается ключевое поле
  • присваивается ячейке А1 листа «Выборка»
  • обрабатывается инфа на листе «Выборка»
  • заполняется лист «Бланк»
  • лист «Бланк» отправляется на печать
  • возвращается на лист «Таблица»

и вот тут проблема:

  • фокус мыши расположен на кнопке «Печать» (лист «Таблица»)
  • а фокус активной ячейки — где-то в недрах таблицы

Подскажите, пожалуйста, как вернуть фокус с мыши на ячейку

Процедура, привязянная к кнопке
[vba]

Код

Private Sub Out_for_Printer_Click()
    Dim i As Integer
    i = ActiveCell.Row    
    If i > 3 Then  ‘ не печатать шапку
        Application.ScreenUpdating = False
        Application.Volatile True
        Worksheets(«Выборка»).Cells(1, 1).Value = Worksheets(«Таблица»).Cells(i, 1).Value
        Worksheets(«Бланк»).PrintOut Copies:=1, Collate:=True
        Application.ScreenUpdating = True
    End If
    Sheets(«Таблица»).Select
End Sub

[/vba]

Заранее спасибо

Сообщение отредактировал Alex59Вторник, 19.02.2019, 12:07

 

Ответить

vikttur

Дата: Вторник, 19.02.2019, 12:14 |
Сообщение № 2

Группа: Друзья

Ранг: Участник клуба

Сообщений: 2941

[vba]

Код

     Dim r As Range

     Set r = ActiveCell
………….
     r.Select
     Set r =Nothing
End Sub

[/vba]

Сообщение отредактировал viktturВторник, 19.02.2019, 12:15

 

Ответить

Alex59

Дата: Понедельник, 01.04.2019, 10:34 |
Сообщение № 3

Группа: Пользователи

Ранг: Прохожий

Сообщений: 2


Репутация:

0

±

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


Excel 2003

Уважаемый vikttur, спасибо за помощь

 

Ответить

Понравилась статья? Поделить с друзьями:
  • Vba узнать что файл excel
  • Vba удалить символы в ячейке excel
  • Vba удаление таблицы word
  • Vba убрать все пробелы в ячейке excel
  • Vba только для чтения word на