Номер ошибки: | Ошибка 2162 | |
Название ошибки: | Microsoft Access Error 2162 | |
Описание ошибки: | A macro set to one of the current field’s properties failed because of an error in a FindRecord action argument.@In the Macro window, change the Search As Formatted argument to Yes. If you want the argument setting to remain No, do all of the following: * | |
Разработчик: | Microsoft Corporation | |
Программное обеспечение: | Microsoft Access | |
Относится к: | Windows XP, Vista, 7, 8, 10, 11 |
Сводка «Microsoft Access Error 2162
Как правило, специалисты по ПК называют «Microsoft Access Error 2162» как тип «ошибки времени выполнения». Разработчики, такие как Microsoft Corporation, обычно проходят через несколько контрольных точек перед запуском программного обеспечения, такого как Microsoft Access. К сожалению, иногда ошибки, такие как ошибка 2162, могут быть пропущены во время этого процесса.
Некоторые пользователи могут столкнуться с сообщением «A macro set to one of the current field’s properties failed because of an error in a FindRecord action argument.@In the Macro window, change the Search As Formatted argument to Yes. If you want the argument setting to remain No, do all of the following: *» при использовании Microsoft Access. В случае обнаруженной ошибки 2162 клиенты могут сообщить о наличии проблемы Microsoft Corporation по электронной почте или сообщать об ошибках. Microsoft Corporation может устранить обнаруженные проблемы, а затем загрузить измененный файл исходного кода, позволяя пользователям обновлять свою версию. Таким образом, когда ваш компьютер выполняет обновления, как это, это, как правило, чтобы исправить проблемы ошибки 2162 и другие ошибки внутри Microsoft Access.
Что запускает ошибку времени выполнения 2162?
Сбой устройства или Microsoft Access обычно может проявляться с «Microsoft Access Error 2162» в качестве проблемы во время выполнения. Проанализируем некоторые из наиболее распространенных причин ошибок ошибки 2162 во время выполнения:
Ошибка 2162 Crash — это распространенная ошибка 2162 во время выполнения ошибки, которая приводит к полному завершению работы программы. Эти ошибки обычно возникают, когда входы Microsoft Access не могут быть правильно обработаны, или они смущены тем, что должно быть выведено.
Утечка памяти «Microsoft Access Error 2162» — ошибка 2162 утечка памяти приводит к тому, что Microsoft Access постоянно использует все больше и больше памяти, увяская систему. Потенциальные триггеры могут быть «бесконечным циклом», или когда программа выполняет «цикл» или повторение снова и снова.
Ошибка 2162 Logic Error — логическая ошибка возникает, когда Microsoft Access производит неправильный вывод из правильного ввода. Обычные причины этой проблемы связаны с ошибками в обработке данных.
Такие проблемы Microsoft Access Error 2162 обычно вызваны повреждением файла, связанного с Microsoft Access, или, в некоторых случаях, его случайным или намеренным удалением. Для устранения неполадок, связанных с файлом Microsoft Corporation, большинство профессионалов ПК заменят файл на соответствующую версию. Более того, поддержание чистоты реестра и его оптимизация позволит предотвратить указание неверного пути к файлу (например Microsoft Access Error 2162) и ссылок на расширения файлов. По этой причине мы рекомендуем регулярно выполнять очистку сканирования реестра.
Классические проблемы Microsoft Access Error 2162
Обнаруженные проблемы Microsoft Access Error 2162 с Microsoft Access включают:
- «Ошибка Microsoft Access Error 2162. «
- «Microsoft Access Error 2162 не является программой Win32. «
- «Извините за неудобства — Microsoft Access Error 2162 имеет проблему. «
- «К сожалению, мы не можем найти Microsoft Access Error 2162. «
- «Отсутствует файл Microsoft Access Error 2162.»
- «Проблема при запуске приложения: Microsoft Access Error 2162. «
- «Не удается запустить Microsoft Access Error 2162. «
- «Ошибка Microsoft Access Error 2162. «
- «Неверный путь к приложению: Microsoft Access Error 2162.»
Эти сообщения об ошибках Microsoft Corporation могут появляться во время установки программы, в то время как программа, связанная с Microsoft Access Error 2162 (например, Microsoft Access) работает, во время запуска или завершения работы Windows, или даже во время установки операционной системы Windows. Документирование проблем Microsoft Access Error 2162 в Microsoft Access является ключевым для определения причины проблем с электронной Windows и сообщения о них в Microsoft Corporation.
Эпицентры Microsoft Access Error 2162 Головные боли
Заражение вредоносными программами, недопустимые записи реестра Microsoft Access или отсутствующие или поврежденные файлы Microsoft Access Error 2162 могут создать эти ошибки Microsoft Access Error 2162.
В частности, проблемы с Microsoft Access Error 2162, вызванные:
- Поврежденные ключи реестра Windows, связанные с Microsoft Access Error 2162 / Microsoft Access.
- Вредоносные программы заразили Microsoft Access Error 2162, создавая повреждение.
- Другая программа (не связанная с Microsoft Access) удалила Microsoft Access Error 2162 злонамеренно или по ошибке.
- Microsoft Access Error 2162 конфликтует с другой программой (общим файлом).
- Microsoft Access (Microsoft Access Error 2162) поврежден во время загрузки или установки.
Продукт Solvusoft
Загрузка
WinThruster 2023 — Проверьте свой компьютер на наличие ошибок.
Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11
Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление
-
#1
I am really confused now — I have some code which works perfectly well for the vast majority of the time, however once in a while it will throw its toys out of the pram and give me an error message ‘Runtime Error 2162’ and states that this is due to an error in the FindRecord Statement; when debugged, it highlights the line of code (below) which is the FindRecord Statement:
Code:
DoCmd.FindRecord EmpNo, acEntire, , acSearchAll, False, acCurrent
Yet, I can see nothing wrong with this code? Surely if the code was duff, it wouldn’t work at all?
The problem seems more likely to happen if the database has not long been opened, if that makes any sort of difference?
I’d be grateful for any help that can be given, as I am not keen on releasing the database into use knowing that its a bit buggy.
-
#2
I think I have solved it by adding a 1 second pause to the code just as it starts (and well before it gets to the FindRecord command) — although I have no idea why this would make a difference?
EDIT — nah, it didn’t. Logged out for a couple of minutes and logged back in and the problem is still there. So frustrating, not least because it is not happening all the time.
Last edited: Sep 16, 2014
-
#3
One problem with DoCmd is that it doesn’t specify an object on which to operate, so it could be that you need to DoCmd.SelectObject or explicitly .SetFocus to something first.
Like, if your DoCmd code is on FormA, and can be (but isn’t always) triggered from FormB, then when the DoCmd code runs and FormB is the currently selected object, maybe then it fails. But this common with DoCmd operations, that sometimes the current object is ambiguous or not what you expect.
-
#4
Thanks @MarkK
I maybe should have shown more of the code to explain more, as the line immediately before the FindRecord line is setting the focus to a bound text box.
Code:
Dim EmpNo
Dim T1 As Variant
Dim T2 As Variant
EmpNo = Me.cboSurnameCheck.Column(2)
If DCount("Employee_Number", "CPC_Incomplete_Training", "Employee_Number='" & EmpNo & "'") > 0 Then
MsgBox "An active training record already exists for this employee. Please select the option to Amend or Edit Existing Training Record.", vbOKOnly
T1 = Now()
T2 = DateAdd("s", 1, T1)
Do Until T2 <= T1
T1 = Now()
Loop
Me.txtEmpSearch.SetFocus
DoCmd.FindRecord EmpNo, acEntire, , acSearchAll, False, acCurrent
Me.lblAmend.Visible = True
Me.cmdAmendYes.Visible = True
Me.cmdAmendNO.Visible = True
Me.cboSurnameCheck = Null
Else
Do a whole load of other stuff with the form
End If
End Sub
I have cut the other bit of the code out as it is quite long and irrelevant to the problem; Although under normal circumstances, there will be at least one more form open, I am currently testing with just the one form open on its own.
For info
- the form’s record source is a query that shows records that are not closed (records are deemed closed when a date is entered in a field, therefore the query returns only records where this field is null)
- the combobox me.cboSurnameCheck is unbound
- all of the code above is an AfterUpdate event on the combo
In simple terms, I am trying to get the code to first of all check to see if a record exists for the employee, based upon their unique employee number; if there is already a record existing, I would like that record to be found (and thus populating the field ID (which is the Primary Key for the record in the training table); when the command buttons are revealed, one of them has the code to open a different form showing the same record that was showing on the previous form, and then close the original form.
If there is another way to get the record ID without using FindRecord, that would allow it to be used when the command buttons become available, then I am all ears
-
#5
Actually, I have an idea — only, I cannot get it to work……. yet.
How about:
Code:
Dim EmpNo
EmpNo = Me.cboSurnameCheck.Column(2)
If DCount("Employee_Number", "CPC_Incomplete_Training", "Employee_Number='" & EmpNo & "'") > 0 Then
MsgBox "An active training record already exists for this employee. Please select the option to Amend or Edit Existing Training Record.", vbOKOnly
Me.lblAmend.Visible = True
Me.cmdAmendYes.Visible = True
Me.cmdAmendNO.Visible = True
Else
Do other stuff which I know already works...
and then on the command button that appears, get it to find the record ID using DLookup?
Code:
Dim varID As Variant
Dim EmpNo
varID = DLookup("ID", "CPC_Incomplete_Training", "Employee_Number='" & EmpNo & "'")
EmpNo = Me.cboSurnameCheck.Column(2)
DoCmd.OpenForm "CPC_New_Amend", , , "ID =" & varID
DoCmd.CLOSE acForm, "CPC_Add", acSaveNo
However, I have got the OpenForm line wrong……?
-
#6
Got it!
Code:
Dim EmpNo EmpNo = Me.cboSurnameCheck.Column(2) If DCount("Employee_Number", "CPC_Incomplete_Training", "Employee_Number='" & EmpNo & "'") > 0 Then MsgBox "An active training record already exists for this employee. Please select the option to Amend or Edit Existing Training Record.", vbOKOnly Me.lblAmend.Visible = True Me.cmdAmendYes.Visible = True Me.cmdAmendNO.Visible = True Else Do other stuff which I know already works...
and then on the command button that appears, get it to find the record ID using DLookup?
Code:
Dim varID As Integer Dim EmpNo EmpNo = Me.cboSurnameCheck.Column(2) varID = DLookup("ID", "CPC_Incomplete_Training", "Employee_Number='" & EmpNo & "'") DoCmd.OpenForm "CPC_New_Amend", , , "ID =" & varID DoCmd.CLOSE acForm, "CPC_Add", acSaveNo
That gets shot of the FindRecord command which was giving the trouble.
-
#7
I never use DoCmd.FindRecord. Mostly what I do with forms is write a sub like this . . .
Code:
Sub GoToID(RecordID As Long)
With Me.RecordsetClone
.FindFirst "RecordID = " & RecordID
If Not .NoMatch Then Me.Bookmark = .Bookmark
End With
End Sub
. . . which searches a clone of the actual recordset in the form. If it gets results, it goes to the record.
But yeah, you can also re-open the form and apply a filter.
Cheers,
-
#8
Thanks — as it is opening a different form (albeit linked to the same record in the table) I think I will leave alone now I have it working.
Is there a reason that DoCmd.FindRecord seems to be a bit unstable? I did a bit of Googling a bit later yesterday, and it appears that its quite common?
-
#9
Access is a collection of softwares, really. Tables and the database engine are provided by Jet. Data access, is provided by DAO or ADODB. Programming is via the VBA IDE. Access, in some ways, is just the Forms and Reports. Everything else you can use independently.
DoCmd is provided by Access, and it does its best to provide a kind of glue amongst the various components, but it was written after the other components in an effort to get them all to play nice.
-
#10
Check that empno is not null before undertaking the findrecord. Perhaps that is the problem.
Ignore that. Clearly this isn’t the issue.
-
#11
I use findrecord, and have never had an issue.
I was on a tablet before, and it was hard to see the posts
this block — what happens if dcount=0? is that the problem.
Code:
If DCount("Employee_Number", "CPC_Incomplete_Training", "Employee_Number='" & EmpNo & "'") > 0 Then
MsgBox "An active training record already exists for this employee. Please select the option to Amend or Edit Existing Training Record.", vbOKOnly
T1 = Now()
T2 = DateAdd("s", 1, T1)
Do Until T2 <= T1
T1 = Now()
Loop
-
#12
Sorry, I can’t seem to get multi-quotes working for some reason.
@MarkK — that makes a bit of sense, as FindRecord worked perfectly well on every other form I have used it on; having said that, I have spent the past day or so altering code to eliminate it wherever possible, as I am aiming to have this database as stable as possible when released into ‘the wild’
@gemma-the-husky — I believe that was the block that I had trouble with; EmpNo was definitely not null, as I was searching for known data (only half a dozen records to search through). In fact, if searching for something that wasn’t there, it behaved perfectly well.
- Forum
- Access Forums
- Forms
- Run-time error 2162, Find window
-
Run-time error 2162, Find window
2162, a macro set to one of the current field’s properties failed because of an error in a FindRecord action argument.
Code:
Me.DeviceSN.SetFocus Docmd.RunCommand acCmdFind Docmd.FindRecord"120613"
Access Find popup form opens but 120613 doesn’t get loaded into it because of this error.
-
Use a filter
Code:
StrFilter = "DeviceSN = " & Me.DeviceSN 'If Number DataType 'StrFilter = "DeviceSN = """ & Me.DeviceSN & """" 'If string DataType Me.Flter = strFilter Me.FilterOn = true
If this helped, please click the star * at the bottom left and add to my reputation- Thanks
-
Remove the second line as it is not needed.
Cheers,
Similar Threads
-
Replies: 3
Last Post: 05-31-2019, 01:52 PM
-
Replies: 10
Last Post: 02-18-2016, 09:44 PM
-
Replies: 1
Last Post: 04-30-2013, 05:44 PM
-
Replies: 3
Last Post: 03-03-2013, 12:22 PM
-
Replies: 1
Last Post: 12-01-2012, 12:44 PM
![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
- BB code is On
- Smilies are On
- [IMG] code is On
- [VIDEO] code is On
- HTML code is Off
Forum Rules
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS
Contact US
Thanks. We have received your request and will respond promptly.
Log In
Come Join Us!
Are you a
Computer / IT professional?
Join Tek-Tips Forums!
- Talk With Other Members
- Be Notified Of Responses
To Your Posts - Keyword Search
- One-Click Access To Your
Favorite Forums - Automated Signatures
On Your Posts - Best Of All, It’s Free!
*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.
Posting Guidelines
Promoting, selling, recruiting, coursework and thesis posting is forbidden.
Students Click Here
find record command «error 2162»find record command «error 2162»(OP) 7 Jun 04 06:54 Hallo I have a single form. I would like to put an unbound text field to use it as a search text box for the whole recordset. The user write something and then click a small «go» button. The code I put behind the button is this: DoCmd.FindRecord [Txt_search], acAnywhere but there is this runtime error 2162: a macro set to one of the current fields properties failed because of an error in a findrecord action argument. Does someone know what’s going on? Red Flag SubmittedThank you for helping keep Tek-Tips Forums free from inappropriate posts. |
Join Tek-Tips® Today!
Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.
Here’s Why Members Love Tek-Tips Forums:
Talk To Other Members
- Notification Of Responses To Questions
- Favorite Forums One Click Access
- Keyword Search Of All Posts, And More…
Register now while it’s still free!
Already a member? Close this window and log in.
Join Us Close
Вот типичный обработчик ошибок для подформы в виде таблицы:
Public Const cErrCodeValueRequierd = 3162
Public Const cErrCodeDuplicateKey = 3022
Private Sub Form_Error(DataErr As Integer, Response As Integer)
Select Case DataErr
Case cErrCodeDuplicateKey
MsgBox "Duplicate records are not allowed!", vbExclamation, "Key violation"
Response = acDataErrContinue
Case cErrCodeValueRequired
MsgBox "Field ""fieldName"" requires data!""
Response = acDataErrContinue
Case Else
MsgBox "Other error. Error code: " & DataErr
End Select
End Sub
Ловушка всех ошибок
Основная обработка ошибок должна быть добавлена ко всем процедурам производственного кода, поскольку в противном случае непредвиденная ошибка приведет к сбою доступа или вызову конечного пользователя для входа в режим отладки.
Типичный шаблон для основного обработчика ошибок, который задерживает все ошибки:
Sub Name()
On Error GoTo errHandler
'[some code...]
exitHandler:
'Clean up any objects
Exit Sub
errHandler:
Select Case Err.Number
'Any expected error cases go here
Case Else
MsgBox Err.Number & Err.Description
End Select
Resume exitHandler 'Make sure objects get cleaned up when code threw an error
End Sub
Более подробное описание обработки ошибок в Access VBA см. В:
- Обработка ошибок в VBA , Аллен Браун
- Советы по ошибкам и методы отладки для Microsoft Access, VBA и Visual Basic 6 (VB6) , Люк Чунг
Ловушка и обработка ошибок в коде пользователя
При ошибке перейдите к помеченному коду и посмотрите, есть ли конкретная ошибка, которая должна быть обработана.
Public Const cErrCodeNotNumber = 2262 ' This value must be a number.
Public Const cErrCodeNumericOverflow = 2263 ' The number is too large.
Private Sub MySub()
Dim objConn As ADODB.Connection
Dim objCmd As ADODB.Command
Dim objRS As ADODB.Recordset
'etc.
On Error Goto ErrHandler
[...My code goes here...]
ExitSub:
'Cleanup
If objConn.State <> adStateOpen Then objConn.Close 'Closing connection to database, if it is still open
If Not objRS Is Nothing Then objRS.Close
objConn = Nothing
ObjRS = Nothing
'Do any other cleaning.
Exit Sub
ErrHandler:
Select Case Err.Number
Case cErrCodeNotNumber
MsgBox "The value found is not a number. Execution stopped.", vbCritical
Case cErrCodeNumericOverflow
MsgBox "The value found is too big. [instructions how to resolve this]", vbCritical
Case Else
MsgBox "Error " & Err.Number & ". " & vbCrLf & Err.Source & "--->" & Err.Description, "Unrecoverable error", vbCritical
End Select
Goto ExitSub
End Sub