Ошибка 2185 access

I getting a run time error 2185, «You can’t reference a property or method for a control unless the control has the focus …».

This is my code that I am using.

Private Sub Command5_Click()
    Dim cardno As Integer
    cardno = cardnumber.Text
    DoCmd.OpenForm "search_card_number", acNormal, , WHERE & cardno = [Account Number]
End Sub

HansUp's user avatar

HansUp

96k11 gold badges77 silver badges135 bronze badges

asked Dec 20, 2013 at 12:17

Steve's user avatar

0

Referencing the .Text property of a control requires it to have focus.
Simply drop that and it should work (the default is .Value)

OR

Try putting in the SetFocus method as advised by Access, i.e.

  Private Sub Command5_Click()
    Dim cardno As Integer

     cardnumber.SetFocus   <-------Use this line to set the focus        

    cardno = cardnumber.Text
  DoCmd.OpenForm "search_card_number", acNormal, , WHERE & cardno = [Account Number]
 End Sub

answered Dec 20, 2013 at 12:35

analyticalpicasso's user avatar

3

That run time error means You can't reference a property or method for a control unless the control has the focus.

You can use .Text when a control has the focus.

answered Dec 20, 2013 at 12:22

Siddharth Rout's user avatar

Siddharth RoutSiddharth Rout

147k17 gold badges206 silver badges250 bronze badges

2

My solution was to test to see if the control had focus before updating the control property,

Here I am updating a combo box search to a wild card search

Private Sub Combo_Change()
    'Note control passed to after update sub, then returns to change sub where error occurs
    'Combo is the name of your combo box

    If (Combo Is Me.ActiveControl) Then
        Me.Combo.RowSource = _
            "SELECT [CCL sites v Contract No].ContractID, [CCL Sites].[Site Address], [CCL sites v Contract No].[Contract No] " & _
            "FROM [CCL sites v Contract No] INNER JOIN [CCL Sites] ON [CCL sites v Contract No].SiteID = [CCL Sites].SiteID " & _
            "WHERE [CCL Sites].[Site Address] LIKE '*" & Me.Combo.Text & "*' " & _
            "ORDER BY [CCL Sites].[Site Address]"

        Me.Combo.Dropdown

    End If

End Sub

Nerdroid's user avatar

Nerdroid

13.4k5 gold badges58 silver badges69 bronze badges

answered Aug 6, 2014 at 23:54

gpgb's user avatar

zakaz_77

9 / 9 / 4

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

Сообщений: 730

1

01.03.2018, 15:40. Показов 4489. Ответов 5

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


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

Код

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Option Compare Database
Dim s0
 
 
' ***  ФИЛЬТР  ***
Private Sub ФрмФлтрПоле_1_Change()
    s0 = "" & Me.ФрмФлтрПоле_1
    Call fpoisk
    Me.ФрмФлтрПоле_1.SelStart = Len(s0) + 1
    
End Sub
 
 
' ***fpoisk()***
Sub fpoisk()
    Dim p, f, masf, masp, s, w, i, k, t
    masf = Array("ФрмФлтрПоле_1") 'Массивы поисковых имен
    masp = Array("Поле_1")      'Массив соответствующих полей таблицы
    
    On Error GoTo errend
    f = Screen.ActiveControl.Name 'Находим имя активного поля поиска
    For i = 0 To UBound(masf) 'В цикле ищем поле таблицы по имени поискового поля
        If f = masf(i) Then
            k = i
            Exit For
        End If
    Next
    If Me(f).Text & "" = "" Then 'Если пусто, то только заносим в Tag пустое значение
        Me(f).Tag = ""
    Else      'Если не пустое, формируем строку фильтра и записываем ее Tag активного контрола
        p = Split(Me(f).Text, ",")
        For i = 0 To UBound(p)
            If p(i) & "" <> "" Then
                s = s & " or [" & masp(k) & "] like '*" & Trim(p(i)) & "*' "
            End If
        Next
        Me(f).Tag = " and (" & Mid(s, 4) & ")"
    End If
    
    'Цикл по все поисковым полям для формирования фильтра
    For i = 0 To UBound(masf)
        If Me(masf(i)).Tag <> "" Then
            w = w & Me(masf(i)).Tag
        End If
    Next
    
    If w <> "" Then 'Если строка фильтра не пустая, задаем фильтр
        w = " true " & w
        Me.Filter = w
        Me.FilterOn = True
    Else
        Me.Filter = ""
        Me.FilterOn = False
    End If
    Me(f).SetFocus 'При пустом поле может уйти фокус. Поэтому насильно возвращаем
 
    Exit Sub
errend:
    MsgBox "Ошибка " & Err.Number & " " & Err.Description
End Sub

При неправильно введённом значении фильтра появляется ошибка
Run-time error’2185′:
Невозможно обратиться к свойству или методу элемента
управления, пока на этот элемент не установлен фокус ввода.

Хотя в другом файле точно такой-же код работает.

Вопрос
Как сделать чтобы при неправильно введённом значении форма не отображала ниодного значения?

Миниатюры

Error'2185'.  Невозможно обратиться к свойству или методу элемента пока нет фокуса
 

Error'2185'.  Невозможно обратиться к свойству или методу элемента пока нет фокуса
 

Вложения

Тип файла: rar vpr.rar (33.0 Кб, 9 просмотров)



0



Модератор

Эксперт MS Access

5423 / 2678 / 661

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

Сообщений: 7,105

01.03.2018, 15:55

2

zakaz_77, все кино снимаете?
И без кино все ясно — в форме запрет на добавление.



1



9 / 9 / 4

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

Сообщений: 730

01.03.2018, 16:04

 [ТС]

3

Capi,
А как сделать чтобы код не обращал внимания на эту ошибку?
Т.е. если ошибка то форма показывает все значения..
Или по другому как-нибудь… не знаю…
В общем чтобы просто ошибку прошёл…

Я пробовал, что-то вроде «On Error Goto», но что-то не работает



0



Capi

Модератор

Эксперт MS Access

5423 / 2678 / 661

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

Сообщений: 7,105

01.03.2018, 16:13

4

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

как сделать чтобы код не обращал внимания на эту ошибку?
Т.е. если ошибка то форма показывает все значения..

Попробуйте:

Visual Basic
1
2
3
4
5
6
7
8
Private Sub ФрмФлтрПоле_1_Change()
    s0 = "" & Me.ФрмФлтрПоле_1
    Call fpoisk
    If Me.Recordset.RecordCount = 0 Then
     Me.FilterOn = False
    End If
    Me.ФрмФлтрПоле_1.SelStart = Len(s0) + 1    
End Sub



1



9 / 9 / 4

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

Сообщений: 730

01.03.2018, 16:19

 [ТС]

5

Capi,
Ошибка осталась.
Т.е. ничего не поменялось



0



Capi

Модератор

Эксперт MS Access

5423 / 2678 / 661

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

Сообщений: 7,105

01.03.2018, 16:42

6

Лучший ответ Сообщение было отмечено zakaz_77 как решение

Решение

Visual Basic
1
2
3
4
5
6
7
8
9
Private Sub ФрмФлтрПоле_1_Change()
    s0 = "" & Me.ФрмФлтрПоле_1
    Call fpoisk
    If Me.Recordset.RecordCount = 0 Then
     Me.FilterOn = False
    End If
    Me.ФрмФлтрПоле_1.SetFocus
    Me.ФрмФлтрПоле_1.SelStart = Len(s0) + 1    
End Sub



1



  • Remove From My Forums

 locked

Access 2010 VBA — Error ‘2185’ — Can’t reference a property unless the control has the focus

  • Question

  • Text box (enabled, not locked, visible) in response to a keystroke returns the following error:

    «Run-time error ‘2185’: You can’t reference a property or method for a control unless the control has the focus.»

    Here is the code:

    Private Sub txtPolicy_Change()
    Debug.Print «txtPolicy_Change»
    Debug.Print »    :» & Screen.ActiveControl.Name
    Debug.Print »        :» & txtPolicy.Text         ‘ <<< Error raised
    End Sub

    The immediate window shows:

    txtPolicy_Change
        :txtPolicy

    The previous event, txtPolicy_KeyPress, fired and also indicated that the Screen.ActiveControl.Name was txtPolicy.

    Seems like during a change event, the control that raised the event should have the focus, especially when the system says it is the active control (perhaps active doesn’t mean has the focus?).

    Thanks for help.  \Gregg


    \Gregg

Answers

  • Well, moving things to the Form Header worked fine.  VERY annoying.  I need to tell self that when something strange happens in Access, I should recreate whatever object I’m working on.  Can’t wait to get back to VS2012.  Thanks for
    you thoughts!


    \Gregg

    • Edited by

      Thursday, May 1, 2014 12:54 AM

    • Marked as answer by
      GSkal
      Thursday, May 1, 2014 12:54 AM

I am having an issue while trying to search in a combo box that dynamically filters a continuous form. The code is as follows:

Private Sub cboFormFilter_Change()

    If Nz(Me.cboFormFilter.Text) = "" Then
        Me.Form.Filter = ""
        Me.FilterOn = False

        ElseIf Me.cboFormFilter.ListIndex <> -1 Then
           Me.Form.Filter = "[Description] = '" & _
              Replace(Me.cboFormFilter.Text, "'", """") & "'"
           Me.FilterOn = True

        Else
           Me.Form.Filter = "[Description] Like '*" & _
              Replace(Me.cboFormFilter.Text, "'", """") & "*'"
           Me.FilterOn = True

    End If

    Me.cboFormFilter.SetFocus
    Me.cboFormFilter.SelStart = Len(Me.cboFormFilter.Text)

End Sub

This code works excellent, but the second I type something that isn’t on the continuous form, it will give me the runtime error «2185′

for example, if my continuous form only has records called ‘Hello World’ and I type in Hello Worlds, it will pop up the error.

I’ve searched around the internet to find out what is going on, but couldn’t figure it out. Other people were having issues similar to the one I am having and they said to remove the .Text, but this still results in the 2185 error. I’m out of ideas and my brain is melted. Any ideas?

asked Nov 17, 2014 at 21:12

Dylan's user avatar

1

Googling ‘runtime error 2185’ yields results about an error that occurs when you’re trying to access a control’s properties without the control having focus (would have been nice to include the error message in your question).

It seems weird that the control wouldn’t be having focus, since it’s that control raising the Change event you’re handling here.

So I’d just wrap the code in an error handler and work it from there:

On Error GoTo CleanFail

    'your code

CleanExit:
    Exit Sub
CleanFail:
    If Err.Number = 2158 Then
        'handle the error - msgbox, whatever
        Err.Clear
        Resume CleanExit
    End If

answered Nov 17, 2014 at 21:32

Mathieu Guindon's user avatar

Mathieu GuindonMathieu Guindon

69.8k8 gold badges107 silver badges235 bronze badges

2

Icon Ex Error Number: Error 2185
Error Name: You can’t reference a property or method for a control unless the control has the focus
Error Description: You can’t reference a property or method for a control unless the control has the focus.@Try one of the following: * Move the focus to the control before you reference the property. In Visual Basic code, use the SetFocus method. In a macro, use the GoToCo
Developer: Microsoft Corporation
Software: Microsoft Access
Applies to: Windows XP, Vista, 7, 8, 10, 11

Analysis of You can’t reference a property or method for a control unless the control has the focus

People often prefer to refer to You can’t reference a property or method for a control unless the control has the focus as a «runtime error», also known as a software bug. Software developers such as Microsoft Corporation usually take Microsoft Access through multiple levels of debugging to weed out these bugs before being released to the public. As much as software developers attempt to prevent it, some minor errors such as error 2185 might not have been found during this phase.

Microsoft Access users might run into the error 2185 caused by normal use of the application, which might also read as, «You can’t reference a property or method for a control unless the control has the focus.@Try one of the following: * Move the focus to the control before you reference the property. In Visual Basic code, use the SetFocus method. In a macro, use the GoToCo». When the bug shows up, computer users will be able to notify the developer about the presence of error 2185 through error reporting. They will then patch the defective areas of code and make an update available for download. If there’s a prompt for a Microsoft Access update, it’s usually a workaround for fixing issues like error 2185 and other bugs.

What Generates Runtime Error 2185?

You will have a failure during execution of Microsoft Access if you run into You can’t reference a property or method for a control unless the control has the focus during runtime. We can identify the origin of error 2185 runtime errors as follows:

Error 2185 Crash — This is a very popular error 2185 runtime error that causes the entire program to shut down. This occurs a lot when the product (Microsoft Access) or computer is unable to handle the unique input data.

You can’t reference a property or method for a control unless the control has the focus Memory Leak — When a Microsoft Access memory leak happens, it will result in the operating system running sluggish due to a lack of system resources. Potential triggers may be endless looping, which causes the program operation to run over and over again.

Error 2185 Logic Error — A logic error happens when Microsoft Access produces wrong output from the right input. This occurs when Microsoft Corporation’s source code triggers vulnerability in information processing.

Microsoft Corporation problems with You can’t reference a property or method for a control unless the control has the focus most often stem from a corrupt or missing Microsoft Access file. Downloading and replacing your Microsoft Corporation file can fix the problem in most cases. Also, maintaining a clean and optimized Windows registry can help in preventing invalid Microsoft Corporation file path references, so we highly recommend running a registry scan on a regular basis.

You can’t reference a property or method for a control unless the control has the focus Errors

You can’t reference a property or method for a control unless the control has the focus Issues Related to Microsoft Access:

  • «You can’t reference a property or method for a control unless the control has the focus Program Error.»
  • «You can’t reference a property or method for a control unless the control has the focus not a Win32 program.»
  • «Sorry for the inconvenience — You can’t reference a property or method for a control unless the control has the focus has a problem.»
  • «You can’t reference a property or method for a control unless the control has the focus can’t be located.»
  • «You can’t reference a property or method for a control unless the control has the focus can’t be found.»
  • «Error starting program: You can’t reference a property or method for a control unless the control has the focus.»
  • «Can’t run You can’t reference a property or method for a control unless the control has the focus.»
  • «You can’t reference a property or method for a control unless the control has the focus failed.»
  • «You can’t reference a property or method for a control unless the control has the focus: App Path is Faulting.»

Usually You can’t reference a property or method for a control unless the control has the focus errors with Microsoft Access happen during startup or shutdown, while You can’t reference a property or method for a control unless the control has the focus related programs are running, or rarely during the OS update sequence. Documenting You can’t reference a property or method for a control unless the control has the focus problem occasions in Microsoft Access is key to determine cause of the Windows problems, and reporting them to Microsoft Corporation.

Source of You can’t reference a property or method for a control unless the control has the focus Errors

Most You can’t reference a property or method for a control unless the control has the focus problems stem from a missing or corrupt You can’t reference a property or method for a control unless the control has the focus, virus infection, or invalid Windows registry entries associated with Microsoft Access.

Chiefly, You can’t reference a property or method for a control unless the control has the focus complications are due to:

  • Invalid You can’t reference a property or method for a control unless the control has the focus or corrupted registry key.
  • Malware has infected You can’t reference a property or method for a control unless the control has the focus, creating corruption.
  • Malicious deletion (or mistaken) of You can’t reference a property or method for a control unless the control has the focus by another application (not Microsoft Access).
  • You can’t reference a property or method for a control unless the control has the focus is in conflict with another program (shared file).
  • Corrupt download or incomplete installation of Microsoft Access software.

Product by Solvusoft

Download Now
WinThruster 2023 — Scan your PC for computer errors.

Compatible with Windows 11, 10, 8, 7, Vista, XP and 2000

Optional Offer for WinThruster by Solvusoft | EULA | Privacy Policy | Terms | Uninstall

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка 2184 служба не запущена
  • Ошибка 218217 на опель астра н z18xer
  • Ошибка 218214 опель зафира б
  • Ошибка 218214 opel astra h
  • Ошибка 2182 опель астра

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: