Vba excel установить курсор в textbox

1508 / 478 / 56

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

Сообщений: 8,008

1

06.04.2011, 19:52. Показов 16018. Ответов 5


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

Подскажите как программировать нахождение курсора в тексбоксе TextBox
1 Если курсор стоит в начале текстбокса???
2 Поставить курсор перед, после последнего знака текстбокса??
3 Выделить n знак в текстбоксе??



0



Busine2009

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

06.04.2011, 20:27

2

Положение курсора в TextBox:

Visual Basic
1
2
3
Private Sub CommandButton1_Click()
MsgBox TextBox1.SelStart
End Sub

Поставить курсор перед, после последнего знака текстбокса??

Visual Basic
1
2
3
4
5
6
Private Sub CommandButton1_Click()
With TextBox1
    .SetFocus
    .SelStart = Len(.Text)
End With
End Sub

Выделение второго знака в TextBox:

Visual Basic
1
2
3
4
5
6
7
Private Sub CommandButton1_Click()
With TextBox1
    .SetFocus
    .SelStart = 1
    .SelLength = 1
End With
End Sub



1



1508 / 478 / 56

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

Сообщений: 8,008

06.04.2011, 20:58

 [ТС]

3

а как будет если курсор в первом положении а пользователь жмёт BackSpace или стрелку влево, чтобы звук был — Beep



0



Busine2009

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

06.04.2011, 21:18

4

Visual Basic
1
2
3
4
5
6
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If TextBox1.SelStart = 0 And KeyCode = 8 Or _
        TextBox1.SelStart = 0 And KeyCode = 37 Then
    Beep
End If
End Sub



0



Ципихович Эндрю

1508 / 478 / 56

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

Сообщений: 8,008

07.04.2011, 09:02

 [ТС]

5

Понял, а как это же самое во всех тексбоксах на форме?

Добавлено через 30 секунд
чтобы к каждому не писать

Добавлено через 11 часов 18 минут

Visual Basic
1
2
3
4
5
6
'код клавищи
lngCode = BuildKeyCode(wdKeyAlt)
'код нескольких клавищ
lngCodesss = BuildKeyCode(wdKeyAlt, wdKeyControl, wdKeyW)
'код клавищи цифровой - имя клавиши
lngCode111 = ??????

Как узнать если есть номер клавиши 8, каково имя клавиши??



0



mc-black

2784 / 716 / 106

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

Сообщений: 1,443

07.04.2011, 09:26

6

В теле макроса набери wdKey и нажми Ctrl+J — выпадет список с тем, что тебя интересует.
Это перечисление WdKey.

Добавлено через 5 минут
Или сделай так:

Visual Basic
1
2
3
4
5
Sub m_1()
    Dim k As WdKey
    
    k =
End Sub

После того, как нажмешь кноку равно и пробел — вывалится весь список перечисления. =)



2



The title mostly explains what I need. I have a textbox that I continuously examine for data validity using the _keypress procedure. If the user enters ( then I auto-fill it for them by typing the closing parenthesis ). The result is () and the cursor is at the end of the textbox.
My question is, how can I push the cursor back one step to put it between the two parenthesis? Thanks,

Edit: Test scenario:

Private Sub txtInput_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

    If KeyAscii = Asc("(") Then
        txtInput.value = txtInput.value & "()"
        KeyAscii = 0
    End If

End Sub

Hope this makes it more clear,

General Grievance's user avatar

asked Feb 8, 2015 at 21:19

Grendizer's user avatar

Use the SelStart property of the TextBox object:

Me.TextBox1.Value = "()"
Me.TextBox1.SelStart = 1

Note: SelStart=1 means the cursor will be after the first element, i.e. «(«. You should hence play with your string to understand what your desired value of SelStart property should be.

answered Feb 8, 2015 at 22:01

Matteo NNZ's user avatar

Matteo NNZMatteo NNZ

11.8k11 gold badges53 silver badges88 bronze badges

4

Use the SelStart property with Len function

Me.txtInput.SelStart = Len(Me.txtInput.Value)-1

Using this method now you can be sure that it will always set the typing cursor between your parenthesis

answered Sep 4, 2022 at 12:56

MoSalah001's user avatar

ZVI

ZVI

MrExcel MVP


  • #2

Hi,
Use this to restore the last edit position in textboxes for Enter / Tab / Shift-Tab navigation:

Rich (BB code):

Private Sub UserForm_Initialize()
  Dim x As Control
  For Each x In Me.Controls
    If TypeOf x Is MSForms.TextBox Then
      x.EnterFieldBehavior = fmEnterFieldBehaviorRecallSelection
    End If
  Next
End Sub

TextBox1.SelStart returns/sets the zero-based start position of selection in TextBox1

Regards

Last edited: Jul 20, 2013

  • #8

Thank you for the post as it proved fruitful for my query.

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

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

Сообщений: 2198


Репутация:

898

±

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


Excel 2010, 2016

AndreyK, методом Activate. Но сначала, нужно выйти из режима редактирования ячейки:
[vba]

Код

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Cancel = True
    With TextBox1
        .Visible = True
        .Value = Cells(ActiveCell.Row, 1).Value
        .Top = ActiveCell.Top
        .Height = ActiveCell.Height + 3
        .Left = ActiveCell.Left
        .Width = ActiveCell.Width  ‘ + 55
        .Activate
     End With
End Sub

[/vba]


ЯД: 410013299366744 WM: R193491431804

In below program, I receive this error: Run-time error ‘-2147467259(80004005)’: Unspecified error. by highlight this code: txtStartDate.SetFocus in this line: If txtStartDate.Text = "" Then txtStartDate.SetFocus

Private Sub txtTimeUnit_Exit(ByVal Cancel As MSForms.ReturnBoolean)

If IsError(Application.Match(txtTimeUnit.Text, Range("intTable[Units]"), 0)) Then
    lblStatusBar = "Please correct value."
    Cancel = True
    Exit Sub
End If

lblStatusBar = vbNullString

Range("CToDate").Value = txtTimeUnit.Text

If txtStartDate.Text = "" Then txtStartDate.SetFocus
If txtEndDate.Text = "" Then txtEndDate.SetFocus

End Sub

Can anyone help me about this error and passing text box focus (Cursor) to another text box?

Shai Rado's user avatar

Shai Rado

32.9k6 gold badges26 silver badges51 bronze badges

asked Jul 2, 2017 at 12:51

mgae2m's user avatar

1

Replace

If txtStartDate.Text = "" Then txtStartDate.SetFocus

by

If txtStartDate.Text = "" Then
    txtStartDate.SetFocus
    Exit Sub
End If

answered Jul 2, 2017 at 13:11

Siddharth Rout's user avatar

Siddharth RoutSiddharth Rout

146k17 gold badges206 silver badges250 bronze badges

8

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